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?

;-)

In reply to Re^4: map and grep (but for hashes) by shmem
in thread map and grep (but for hashes) by zerohero

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.