in reply to Re^4: The Anomalous each()
in thread The Anomalous each()
There is a lot of stuff in perl that isn’t necessary. We don’t need for, foreach, and while. We can get away with just while.
The examples you bring up offer mental shortcuts for specialised scenarios.
Now observe:
while( my $k = each %hash ) { ... } foreach my $k ( keys %hash ) { ... }
Except for the added pitfall of each, these are completely identical. each is no mental shortcut for keys, or vice versa. It merely exposes an implementation detail for when you need to know about it. In Perl6, there won’t even be any sort of difference, and all these constructs will use the same syntactic constructs. Without the difference in implementation detail, any distinction is pointless.
For some people, rewriting to use keys may seem like too large of a change to the code, whereas using an iterator that otherwise feels like each may seem like the code is changing as little as possible.
You can rewrite
while( my ( $k, $v ) = each %hash ) {
as either
foreach my $k ( keys %hash ) { my $v = $hash{ $k };
or
sub each_iter(%) { my $hash = shift; my @keys = keys %$hash; sub { my $nkey = shift @keys; $nkey => $hash->{$nkey}; } } my $iter = each_iter %some_hash; while( my ( $k, $v ) = $iter->() ) {
Which one is least invasive is your call.
Makeshifts last the longest.
|
|---|