in reply to Re^3: map and grep (but for hashes)
in thread map and grep (but for hashes)

Okay... now here's the next quick shot after some trying. Have to look at the failed attempts. This really a fun challenge, zerohero++ ;-)

Since $_ is localized for map and grep, it seems the most natural thing to localize @_ for that purpose, and it seems to work... (update: heh, but it hasn't to be localized - perl does that for us)

#!perl -l # sub hmap (&%) { my $code = shift; @_ % 2 and die "odd number of variables for hmap"; my @i = @_; my @rv; push @rv, $code->(@_=(shift @i,shift @i)) while @i; @rv; } sub hgrep (&%) { my $code = shift; @_ % 2 and die "odd number of variables for hgrep"; my @i = @_; my @rv; for(my $i = 0; $i<= $#_; $i+=2) { local @_ = ($_[$i],$_[$i+1]); $code->(@_) and push @rv, @_; } @rv; } %h = (foo => 1, bar => 2, baz => 3); %new = hmap { $_[0]."l",++$_[1] } %h; print "hmap result:"; print "$_ => $new{$_}" for keys %new; print "original \%h:"; print "$_ => $h{$_}" for keys %h; %new = hgrep { $_[0] =~ /f/ and ($_[0].="l") and $_[1] =~ /1/ and $_[1] += 41; } %h; print "hgrep result:"; print "$_ => $new{$_}" for keys %new; print "original \%h:"; print "$_ => $h{$_}" for keys %h; __END__ hmap result: bazl => 4 barl => 3 fool => 2 original %h: bar => 2 baz => 3 foo => 1 hgrep result: fool => 42 original %h: bar => 2 baz => 3 foo => 1

No package vars introduced. But it looks like in hgrep localizing @_ is necessary, however in hmap it isn't. Why?

;-)

Replies are listed 'Best First'.
Re^5: map and grep (but for hashes)
by ikegami (Patriarch) on Jan 30, 2009 at 23:58 UTC
    local @_ = ($_[$i],$_[$i+1]); $code->(@_) and push @rv, @_;

    is the same as

    my @args = ($_[$i],$_[$i+1]); $code->(@args) and push @rv, @args;

    Did you mean the following (which allows elements to be added and removed from @_) or did you repurpose a package variable for nothing?

    local @_ = ($_[$i],$_[$i+1]); &$code and push @rv, @_;

      I confess, I did repurpose a package variable for nothing. I'm going to abstain from PerlMonks for some hours to do penitence, and bonk my head... ;-)