views:

81

answers:

2

Hi folks.

I have a array like this:

my @arr = ("Field3","Field1","Field2","Field5","Field4");

Now i use map like below , where /DOSOMETHING/ is the answer am seeking.

my %hash = map {$_ => **/DOSOMETHING/** } @arr

Now I require the hash to look like below:

Field3 => 0
Field1 => 1
Field2 => 2
Field5 => 3
Field4 => 4

Any help?

+6  A: 
%hash = map { $arr[$_] => $_ } 0..$#arr;

print Dumper(\%hash)
$VAR1 = {
          'Field4' => 4,
          'Field2' => 2,
          'Field5' => 3,
          'Field1' => 1,
          'Field3' => 0
        };
unbeli
+5  A: 
my %hash;
@hash{@arr} = 0..$#arr;
eugene y
nice one. perl keeps surprising me, after so many years :)
unbeli
It's a shame `%hash` has to be pre-declared, so we can't write something like `my @hash{@arr} = 0 .. $#arr;`...
Zaid
@Zaid There are always cute tricks such as `@$_{@arr} = 0 .. $#arr for \my %hash;`, but eugene's code has less shock value.
Greg Bacon
@gbacon : Agreed, one shouldn't sacrifice readability for one-line-cramming. It's just that I would've imagined that Perl could auto-vivify with array slices as well.
Zaid
@Zaid Your proposed syntax would be nice. You should send a patch to p5p!
Greg Bacon