in reply to Re: map and grep (but for hashes)
in thread map and grep (but for hashes)
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... ;-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: map and grep (but for hashes)
by BrowserUk (Patriarch) on Jan 30, 2009 at 21:07 UTC | |
by shmem (Chancellor) on Jan 30, 2009 at 22:23 UTC | |
by ikegami (Patriarch) on Jan 30, 2009 at 23:58 UTC | |
by shmem (Chancellor) on Jan 31, 2009 at 00:09 UTC | |
by zerohero (Monk) on Jan 30, 2009 at 21:14 UTC | |
by BrowserUk (Patriarch) on Jan 31, 2009 at 00:30 UTC | |
by zerohero (Monk) on Feb 01, 2009 at 20:07 UTC | |
by Corion (Patriarch) on Feb 01, 2009 at 20:15 UTC | |
by BrowserUk (Patriarch) on Feb 02, 2009 at 06:09 UTC | |
| |
|
Re^3: map and grep (but for hashes)
by zerohero (Monk) on Jan 30, 2009 at 21:00 UTC |