in reply to Re: hmap revisited
in thread hmap revisited

I copy and pasted the code sample from above, but it failed to compile. I tried a few things but couldn't get it to work (the error is in the dense part where I don't fully understand the syntactical rules). Offending line seems to be:

snippet:

my %new2 = hmap { $_[1]{nick} =~ /rbush|fred/ ? $_[0] => { hmap { $_[0], $_[1] } %{$_[1]} } : () } %$h;

Here's the compilation error:

bash-3.2$ perl hmap_good2.pl syntax error at hmap_good2.pl line 39, near "] =>" syntax error at hmap_good2.pl line 40, near ":" Execution of hmap_good2.pl aborted due to compilation errors.

Possibly I'm missing something simple? Full script pasted below:

use Data::Dumper; my $h = { 1 => { nick => 'rbush', phone => '5551212', bday => '3/12/1965', }, 3 => { nick => 'ernest', phone => '5553300', bday => '3/12/1971', }, 5 => { nick => 'fred', phone => '1112300', bday => '5/01/1972', }, }; sub hmap (&$) { my $code = shift; my @i = %{ shift() }; my @rv; push @rv, $code->(shift @i,shift @i) while @i; return { @rv }; } my %new2 = hmap { $_[1]{nick} =~ /rbush|fred/ ? $_[0] => { hmap { $_[0], $_[1] } %{$_[1]} } : () } %$h; print Dumper ($new2), "\n";

Note that the second version (the hash ref one) has the same compile error, but I could get that to work by surrounding the returned hash in "()", i.e.:

my $new2 = hmap { $_[1]{nick} =~ /rbush|fred/ ? ($_[0] => hmap { $_[0], $_[1] } $_[1]) : () } $h;

Replies are listed 'Best First'.
Re^3: hmap revisited
by ikegami (Patriarch) on Feb 01, 2009 at 19:49 UTC
    Just a precedence issue. Add parens.
    my %new2 = hmap { $_[1]{nick} =~ /rbush|fred/ ? ( $_[0] => { hmap { $_[0], $_[1] } %{$_[1]} } ) : () } %$h;
    my $new2 = hmap { $_[1]{nick} =~ /rbush|fred/ ? ( $_[0] => hmap { $_[0], $_[1] } $_[1] ) : () } $h;