[英]convert array to hash using grep and map in perl
我有一個數組如下:
@array = ('a:b','c:d','e:f:g','h:j');
如何使用grep和map將其轉換為以下內容?
%hash={a=>1,b=>1,c=>1,d=>1,e=>1,f=>1,h=>1,j=>1};
我試過了:
@arr;
foreach(@array){
@a = split ':' , $_;
push @arr,@a;
}
%hash = map {$_=>1} @arr;
但是我正在獲取所有值我應該獲取單個數組的前兩個值
非常簡單:
%hash = map {$_=>1} grep { defined $_ } map { (split /:/, $_)[0..1] } @array;
因此,您使用“:”定界符分割每個數組元素,得到更大的數組,僅獲取2個第一個值; 然后使用grep定義值並將其傳遞給其他地圖匹配鍵/值對。
您必須忽略除split
之后的前兩個元素之外的所有內容,
my @arr;
foreach (@array){
@a = split ':', $_;
push @arr, @a[0,1];
}
my %hash = map {$_=>1} @arr;
使用地圖
my %hash =
map { $_ => 1 }
map { (split /:/)[0,1] }
@array;
我認為這應該工作,盡管不夠優雅。 我使用一個臨時數組來保存split
的結果並返回前兩個元素。
my %hash = map { $_ => 1 } map { my @t = split ':', $_; $t[0], $t[1] } @array;
這會過濾出g
鍵
my %hash = map { map { $_ => 1; } (split /:/)[0,1]; } @array;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.