pavan
pavan

Reputation: 314

convert array to hash using grep and map in perl

I have an array as follows:

@array = ('a:b','c:d','e:f:g','h:j');

How can I convert this into the following using grep and map?

%hash={a=>1,b=>1,c=>1,d=>1,e=>1,f=>1,h=>1,j=>1};

I've tried:

 @arr;

 foreach(@array){
    @a = split ':' , $_;
    push @arr,@a;

 } 


  %hash = map {$_=>1} @arr; 

but i am getting all the values i should get first two values of an individual array

Upvotes: 0

Views: 3145

Answers (4)

hwnd
hwnd

Reputation: 70732

This filters out g key

my %hash = map { map { $_ => 1; } (split /:/)[0,1]; } @array;

Upvotes: 1

styxyang
styxyang

Reputation: 96

I think this should work though not elegent enough. I use a temporary array to hold the result of split and return the first two elements.

my %hash = map { $_ => 1 } map { my @t = split ':', $_; $t[0], $t[1] } @array;

Upvotes: 1

mpapec
mpapec

Reputation: 50637

You have to ignore everything except first two elements after split,

 my @arr;
 foreach (@array){
    @a = split ':', $_;
    push @arr, @a[0,1];
 } 

  my %hash = map {$_=>1} @arr; 

Using map,

my %hash =
  map { $_ => 1 }
  map { (split /:/)[0,1] }
  @array;

Upvotes: 1

Galimov Albert
Galimov Albert

Reputation: 7357

Its very easy:

%hash = map {$_=>1} grep { defined $_ } map { (split /:/, $_)[0..1] } @array;

So, you split each array element with ":" delimiter, getting bigger array, take only 2 first values; then grep defined values and pass it to other map makng key-value pairs.

Upvotes: 4

Related Questions