"Also please do not recommend using map in void context."

In general, I agree with this statement.

"This is considered bad practice by many programmers since you are only making the call for its side-effects whilst throwing away its output."

However, I disagree with this reason.

The issue with "throwing away its output" was resolved, about 14 years ago[perlhist], in Perl 5.8.1. From "perl581delta: Miscellaneous Enhancements":

"map in void context is no longer expensive. map is now context aware, and will not construct a list if called in void context."

The reason I would give for not using map in void context is based on efficiency. I've had reason to benchmark map vs. for on a number of occasions over the years: I've always found for to be measurably faster than map; and, unsurprisingly, map EXPR is faster than map BLOCK.

Here's a very quick and dirty benchmark I just wrote to show this:

#!/usr/bin/env perl use strict; use warnings; use Benchmark 'cmpthese'; my @x = 0 .. 99; cmpthese 1e6 => { map_expr => sub { my @y = @x; map ++$_, @y; return }, map_block => sub { my @y = @x; map { ++$_ } @y; return }, for => sub { my @y = @x; ++$_ for @y; return }, };

I ran this five times. All results were much the same. This one was roughly in the middle:

Rate map_block map_expr for map_block 75019/s -- -44% -47% map_expr 134953/s 80% -- -5% for 141844/s 89% 5% --

Benchmark run using:

$ perl -v | head -2 | tail -1 This is perl 5, version 26, subversion 0 (v5.26.0) built for darwin-th +read-multi-2level

— Ken


In reply to Re^3: Open Filehandle once by kcott
in thread Open Filehandle once by Dunkellbusch

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.