Wonderful! But slightly off the specs. Well, perhaps. ;-)

#!perl -l # sub hmap (&%) { my $code = shift; local $_; my @rv; push @rv, shift, $code->($_=shift) while @_; @rv; } sub hgrep (&%) { my $code = shift; local $_; my @rv; push (@rv, ($code->($_=$_[1]) ? (shift,$_):())),shift while @_; @rv; } %h = (foo => 1, bar => 2, baz => 3); %new = hmap { ++$_ } %h; print "hmap result:"; print "$_ => $new{$_}" for keys %new; %new = hgrep { /2/ } %h; print "hgrep result:"; print "found $_ => $new{$_}" for keys %new; __END__ hmap result: bar => 3 baz => 4 foo => 2 hgrep result: bar => 2

update: well, this operates on the value only, localizing $_ and doesn't create package vars. For the key... hm. What do we have? $", $/, $\ ... - no, they could be used inside the block. But then... we could localize @_ here!

sub hmap (&%) { my $code = shift; my @i = @_; local @_; my @rv; push @rv, $code->(@_=(shift @i,shift @i)) while @i; @rv; } %h = (foo => 1, bar => 2, baz => 3); %new = hmap { $_[0]."l",++$_[1] } %h; print "hmap result:"; print "$_ => $new{$_}" for keys %new; __END__ hmap result: bazl => 4 barl => 3 fool => 2

update 2: BrowserUk, as you may have noticed, I ommitted the 'hgrep' part here, since my solution doesn't work - seem to not dunno how to change its arguments inside the block... ;-)


In reply to Re^2: 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.