The map Function
There’s one more really cool thing in this script.
Buried in its latter half, where the top-level page is being created
to list all the results stored in the %data
HoH,
there is the following somewhat scary-looking line:
my @engine_links = map { qq{<A HREF="#$_">$_</A>} } sort @engines;
This is our first use of Perl’s map
function. The map
function is another one of those
things, like the conditional operator (walnuts ? rutabagas : watermelons
), that serves to separate the accidental
programmers from the real ones. It took me years, literally, before I
was comfortable enough with Perl to begin using the
map
function, but now that I’m familiar with
it I can’t imagine life without it. Larry
Rosler, one of
the nicest members of the extended Perl community when it comes to
helping out beginners, called the map
function
“beautiful” in a session I attended at one of
O’Reilly’s Perl conferences, and after working with it
for a while I can appreciate why he feels that way.
The map
function is one of those Perl shortcuts, a
diagonal path offering a more efficient route from point A to point
B. In effect, it lets us take a foreach
loop and
squash it down into a single line. To be more specific,
map
lets us specify a block of code to be executed
for each element in a list. The map
function
processes the list, running the block of code on each element, and
returns a list consisting of the results of all those blocks’
execution.
An example will clarify what I’m describing. Let’s ...
Get Perl for Web Site Management now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.