Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^3: Indepedent lazy iterators for the same hash?

by hdb (Prior)
on Jun 30, 2013 at 21:00 UTC ( #1041651=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Indepedent lazy iterators for the same hash?
in thread Indepedent lazy iterators for the same hash?

Just an idea: use each as the master iterator somewhere hidden, and have references pointing to the lagging pseudo-iterators. Will try tomorrow to build something.

UPDATE: Here is my attempt. I am not sure whether it works like each as there is absolutely no magic in it. I am sure it will ignore changes in the hash while you iterating over it.

use strict; use warnings; sub hashIteratorFactory { my $h = shift; my @both; my $exhausted = 0; return sub { my $i = 0; return sub { my ($k, $v); if( !defined $both[$i] ) { if( !$exhausted and (( $k, $v ) = each %$h) ) { push @both, [ $k, $v ]; } else { $exhausted = 1; $i = 0; return wantarray() ? () : undef(); } } else { ( $k, $v ) = @{$both[$i]}; } $i++; return wantarray() ? ( $k, $v ) : $k; } } } my %h; @h{'a'..'d'} = 1..4; my $factory = hashIteratorFactory( \%h ); my $i1 = $factory->(); my $i2 = $factory->(); print "1:",$i1->(),"\n"; print "1:",$i1->(),"\n"; print "2:",$i2->(),"\n"; print "1:",$i1->(),"\n"; print "1:",$i1->(),"\n"; print "2:",$i2->(),"\n"; print "2:",$i2->(),"\n"; print "1:",$i1->(),"\n"; print "1:",$i1->(),"\n"; print "2:",$i2->(),"\n"; print "2:",$i2->(),"\n"; my $i3 = $factory->(); while( my ($k, $v) = $i3->() ) { print "3:$k$v\n"; } print "2:",$i2->(),"\n"; print "1:",$i1->(),"\n";

EDIT: added another wantarray ? to the final return line


Comment on Re^3: Indepedent lazy iterators for the same hash?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1041651]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (10)
As of 2014-11-26 13:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (170 votes), past polls