I'm working on some code which lets me do, amongst other things, this:
my $array = Array::AsHash->new({array => \@array}); while (my ($key, $value) = $array->each) { print "$key : $value\n"; }
That works fine. It let's me lazily pull elements off of the array two by two. When it's done, it resets the internal index so it can do it again.
The problem lies in the following:
while (my ($key, $value) = $array->each) { last if some_condition($key, $value); }
If I exit the loop early, the counter doesn't get reset. "Fine", I thought. "I'll just mark my position with caller and if each() isn't called from the same spot, automatically reset the index."
Doesn't work.
my $count = 0; while ( my $line = get_line_no() ) { # Line 2 print "Line $line\n"; last if $count++; # Line 4 } sub get_line_no { (caller)[2] } __END__ Line 2 Line 4
Any idea how to get around something like this? (For the Shakespeare fans out there, I know that "wherefore" actually means "why" but that still seems an appropriate question).
If you're really curious, here's a very stripped down implementation:
package Array::AsHash; use warnings; use strict; use Class::Std; { my ( %array_for, %last_each_from, %current_index_for ) : ATTRS; sub BUILD { my ( $class, $ident, $arg_ref ) = @_; my $array = $arg_ref->{array} || []; $array_for{$ident} = $array; } sub each { my $self = shift; my $ident = ident $self; my $index = $current_index_for{$ident} || 0; my $caller = join '', caller; if ( ( $last_each_from{$ident} || '' ) ne $caller ) { # calling from a different line. Reset the index and ca +ller $index = $current_index_for{$ident} = 0; $last_each_from{$ident} = $caller; } my @array = @{ $array_for{$ident} }; if ( $index >= @array ) { $current_index_for{$ident} = 0; return; } my ( $key, $value ) = @array[ $index, $index + 1 ]; $current_index_for{$ident} += 2; return ( $key, $value ); } } 1;
And you can test that with:
my @array = qw/key value key1 value1 key2 value2/; use Array::AsHash; $array = Array::AsHash->new( { array => \@array } ); while (my ($k,$v) = $array->each) { print "$k : $v\n"; } __END__ key : value key : value key1 : value1 key2 : value2
Cheers,
Ovid
New address of my CGI Course.
In reply to Caller, caller, wherefore art thou, caller? by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |