Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: map-like hash iterator

by jdporter (Canon)
on Nov 06, 2002 at 20:15 UTC ( #210872=note: print w/replies, xml ) Need Help??


in reply to map-like hash iterator

One further note: this uses the package variables $a and $b to communicate the current key and value to the callback. Therefore, this code must be included (e.g. via "require") in each and every namespace where you want to use it.

As an enhancement, we'd like to avoid the overhead of constructing the result list if the caller won't be using it. --

sub hasheesh(&\%) { my( $c, $h ) = @_; local( $a, $b ); if ( wantarray ) # list context { @_ = (); while ( ( $a, $b ) = each %$h ) { push @_, $c->(); } return @_; } elsif ( defined wantarray ) # scalar context { my $n; while ( ( $a, $b ) = each %$h ) { my @a = $c->(); $n += @a; } return $n; } else # void context { while ( ( $a, $b ) = each %$h ) { $c->(); } } }

Replies are listed 'Best First'.
Re^2: map-like hash iterator
by ikegami (Pope) on Mar 26, 2010 at 23:11 UTC

    One further note: this uses the package variables $a and $b to communicate the current key and value to the callback. Therefore, this code must be included (e.g. via "require") in each and every namespace where you want to use it.

    No, not good enough. The package used is the package in which the source code was found.

    Fix:

    sub hasheesh(&\%) { my( $c, $h ) = @_; local( $a, $b ); { no strict 'refs'; *{caller().'::a'} = \$a; *{caller().'::b'} = \$b; } ...rest... }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://210872]
help
Chatterbox?
shmem serves tea along with the cookies. (☕) x @CBMonks
[shmem]: hmm.. which makes emerge the question: is there a way to attach a subroutine to a variable, which is run as soon as that variable changes?
[moritz]: through a tie?
[shmem]: moritz: of course!
shmem slaps forehead m(
[shmem]: consider, then, @CBMonks as a tied variable which triggers withdrawing empty cups and serving new ones

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2017-04-24 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (439 votes). Check out past polls.