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.


In reply to Re^5: The Anomalous each() by Aristotle
in thread The Anomalous each() by jdhedden

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.