in reply to 'each' syntax oddity?
for a clue, try print ref {qw/1 2 3/}
for an interesting tidbit run
perl -we"sub f{{@_}};print ref(f(1,2,3))"
and then
perl -we"sub f{return {@_}};print ref(f(1,2,3))"
from perldoc -f each
...There is a single iterator for each hash, shared by all "each", "keys", and "values" function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating "keys HASH" or "values HASH". If you add or delete elements of a hash while you're iterating over it, you may get entries skipped or duplicated, so don't. Exception: It is always safe to delete the item most recently returned by "each()"...now you probably have a better idea of what a hash is versus what an array is ... most likely the only reason no automagic happens is because it's not come up before, and isn't that particularly useful.
Also note that the order of the values of @array will not stay in the same order they were in, because this is a hash, but of course pairs will stay pairs ;)
update jmcnamara says the above creates an infinate loop; well that it does, but you gotta admit, it's an ingenious way to get random pairs ;)
you're probably better off writing something like
but that will of course modify @arraywhile(my($one,$two)=(shift(@aray),shift(@aray)) ) { ... #or even while(my($one,$two) = splice(@aray,0,2) ) { ...
update: I thought about getting smart, so I tried
but that WORKSmy @array = qw/ 1 2 3 4/; while(my($one,$two) = Each(\@array) ) { print "$one = $two \n"; } sub Each { my $r = shift; my $counter; unless(@$r) { warn "empty array"; return; } unless($r->[-2] eq $r) { push(@$r, $r); push(@$r,0); } $counter = $r->[-1]; my $one = $counter < scalar(@$r) - 3 ? $r->[$counter] : undef; $counter++; my $two; if( $counter < scalar(@$r) - 2 ) { $two = $r->[$counter]; } else { warn "finally gone through it"; return; } $r->[-1] = $counter; if(2 == @$r) { warn "gone trhough it, nothing left to see"; return; } return ($one, $two); }
F:\dev>perl each.pl 1 = 2 2 = 3 3 = 4 finally gone through it at each.pl line 32.If you plan on using the array later, you'll probably want to pop off the last 2 values ;)(it's be a nice method for your package, make it private, prepend a _)
| ______crazyinsomniac_____________________________ Of all the things I've lost, I miss my mind the most. perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;" |
|
|---|