Inadvertent Inconsistencies: each in Perl 5.12

The explanation of changes in Perl 5.12 includes an innocent looking entry. In its entirety, it reads:

each, keys, values are now more flexible   The each, keys, values function can now operate on arrays.

While there's often little use to using keys and values on arrays, each has one fantastic use: managed iteration over an array which provides access both to the index of the iteration and the current iterator value:

my @chapters = get_chapters( ... );

while (my ($number, $chapter) = each @chapters)
{
    say "Chapter $number: ", $chapter->title;
}

This feature is great, especially when walking over multiple arrays in parallel, or any time you want to let Perl handle the little details it already tracks for you (instead of having to write unnecessary structural code).

Repurposing each (and keys and values) to work on arrays as well as hashes has benefits and drawbacks. There are no conflicts with user-defined functions, as these keywords have existed for longer than I've been using Perl. Semantically they perform somewhat similar functions, even though the aggregates on which they work are different.

The main drawback is that the operators themselves have to become polymorphic, in the sense that their behavior depends on the type of data provided.

We take it for granted that Perl does the right thing when we use == to compare numbers for equality and eq to compare strings for equality. That's why we use . to concatenate strings in Perl 5 and + to add numbers; we make our intent unambiguous.

(If you've never understood monomorphic operators and the degree to which they prevent errors and express programmer intent in Perl, the Modern Perl book includes an explanation of type contexts intended to make these ideas clear. It's free to download and to redistribute.)

Is this change in operator philosophy a problem? Not by itself.

Next time: Perl 5.14 adds a feature.

Modern Perl: The Book

cover image for Modern Perl: the book

The best Perl Programmers read Modern Perl: The Book.

sponsored by the How to Make a Smoothie guide

Categories

Pages

About this Entry

This page contains a single entry by chromatic published on March 19, 2012 9:37 AM.

Avoid Shipping at all Costs was the previous entry in this blog.

Inadvertent Inconsistencies: Aggregate Autoderef in 5.14 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.


Powered by the Perl programming language

what is programming?