in reply to Re^2: map vs for\foreach.
in thread map vs for\foreach.

It isn't wrong, it is just not saying what you mean. map is a transformation. for is a loop. If I use map, it is understood that there are to be no modifications to the original data set (and conversely, if there are side effects, I did it wrong). If I use for, then there is the potential for modification of the original data.

It is, for me, about clarity of intent. That is why I insist (in my code) on this usage.

--MidLifeXis

Replies are listed 'Best First'.
Re^4: map vs for\foreach.
by LanX (Saint) on Mar 13, 2015 at 18:56 UTC
    > If I use map, it is understood that there are to be no modifications to the original data set

    I was meditating if map should be changed in this respect.

    Questions:

    • are there use cases where a new list is returned and the old list needs to be altered by alias?
    • if yes, should we introduce a non aliasing default var to avoid this trap? something like $__ or so?
    The usual workaround is to copy $_, like in

    DB<111> @b = map {my $x=$_; ++$x} @a => (2 .. 11) DB<112> @a => (1 .. 10)

    Then again its pretty easy to replace ++$_ with $_+1 and s/x/y/ with s/x/y/r in current Perl versions.

    Not sure if there are any modifying operators left without a non-modifying counterpart.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)

    PS: Je suis Charlie!

Re^4: map vs for\foreach.
by karlgoethebier (Abbot) on Mar 13, 2015 at 18:23 UTC
    "... if there are side effects, I did it wrong"

    Yes, yes. But you can do what you want: You get the side effect for free - even if you don't want it.

    #!/usr/bin/env perl use strict; use warnings; use Data::Dump; my @original_data_set = ( 1 .. 10 ); dd \@original_data_set; my @modified_data_set = map { ++$_ } @original_data_set; dd \@original_data_set, \@modified_data_set; __END__ karls-mac-mini:monks karl$ ./1119774.pl [1 .. 10] ([2 .. 11], [2 .. 11])

    Best regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

      I think, in this case, that we are firmly entrenched in opposite camps, and will just have to agree to disagree. :-)

      --MidLifeXis

        > just have to agree to disagree

        No I disagree, you two won't agree on that.

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)

        PS: Je suis Charlie!

        ;-)