in reply to Re: Can this script be Optimized?
in thread Can this script be Optimized?

In the interest of education, map is a "feature enhanced" version of for.

map { expr; } @array; is equivalent to:

for (@array) { push @newarray, expr; }

Presumably, expr uses $_ either implicitly or explicitly.

Similarly, grep { expr; } @array; is equivalent to:

for (@array) { push @newaray, $_ if expr; }

Replies are listed 'Best First'.
Re^3: Can this script be Optimized?
by kcott (Archbishop) on May 01, 2014 at 17:03 UTC

    Actually, I'd say a closer equivalency would be

    my @newarray = map { expr } @array;

    and

    my @newarray; for (@array) { push @newarray, expr; }

    Or, conversely

    map { expr } @array;

    and

    for (@array) { expr; }

    or

    expr for @array;

    Anyway, as that was a reply to my post, were you suggesting I replace a map with a for, or vice versa? Or, perhaps, something else?

    -- Ken

      No, just pointing out that map (and grep) are basically equivalent to for. But like many other features of Perl, they can make some things easier to code and easier to read.

      Your point is correct. One additional detail is that a new array (actually list) is always created.

      So, it would really be more like:

      { my $newarray; for (@array) { push @newarray, expr; } @newarray; }
        "One additional detail is that a new array (actually list) is always created."

        That sounds like you're referring to map; if so, that changed in 5.8.1 (over a decade ago).

        From perl581delta: Miscellaneous Enhancements:

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

        I don't follow what you're trying to show with that code in the anonymous block. What does the "it" in "So, it would really be more like:" refer to? Is the anonymous block supposed to be a do {...} block? And $newarray is probably a typo.

        -- Ken