0

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

2
  • Are you wanting g also? Commented Jun 22, 2013 at 5:00
  • @JasonGray: He says, ”i should get first two values of an individual array” Commented Jun 22, 2013 at 11:16

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Borodin Thats cus if split return array with size 1, slice [0..1] will return 2 elements anyway.
1

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;

Comments

1

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;

Comments

1

This filters out g key

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.