awohld has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to figure out how to apply 'map' to this problem.

I want to take my %hash and create a new %new_hash out of it.
I need to swap the key with the first array element that the has points to.

In so I want to %hash to go from:

$hash{'one'} = [ '1', 'two', 'three']; $hash{'two'} = [ '2', 'three', 'four']; $hash{'three'} = [ '3', 'four', 'five'];
to the new %new_hash:
$hash{'1'} = [ 'one', 'two', 'three']; $hash{'2'} = [ 'two', 'three', 'four']; $hash{'3'} = [ 'three', 'four', 'five'];
Here is my example script;
#!/usr/bin/perl -w use strict; use Data::Dumper; my %hash; $hash{'one'} = [ '1', 'two', 'three']; $hash{'two'} = [ '2', 'three', 'four']; $hash{'three'} = [ '3', 'four', 'five']; # Here is where I can't get 'map' quite right my %new_hash = map { $_->[0] => [ getkey($_), $_->[1], $_->[2] ] }; print Dumper \%new_hash;

Replies are listed 'Best First'.
Re: Using MAP to swap around HoA hash keys and array values.
by ysth (Canon) on Jun 11, 2006 at 19:56 UTC
    The "key" :) is that map only iterates over one element at a time, so you want to feed it the keys of the old hash.
    my %new_hash = map { $hash{$_}[0] => [ $_, @{$hash{$_}}[1,2] ] } keys +%hash;
Re: Using MAP to swap around HoA hash keys and array values.
by planetscape (Chancellor) on Jun 11, 2006 at 20:26 UTC
Re: Using MAP to swap around HoA hash keys and array values.
by ambrus (Abbot) on Jun 11, 2006 at 20:39 UTC

    Let's see.

    my %new_hash = map { my $v = $hash{$_}; $$v[0], [$_, @$v[1 .. @$v - 1] +] } keys(%hash);
      @$v - 1

      You meant $#$v. @$v - 1 is taking a wrong value and fixing it make it right. $#$v is already right. You should prefer the value that is already right to prevent accidentally getting an off-by-one if you ever forget to include the fixing -1.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re: Using MAP to swap around HoA hash keys and array values.
by jwkrahn (Abbot) on Jun 11, 2006 at 21:49 UTC
    my %new_hash = map { splice( @{ $hash{ $_ } }, 0, 1, $_ ), [ @{ $hash{ + $_ } } ] } keys %hash;