in reply to Re: Balancing Coding Time And Code Quality
in thread Balancing Coding Time And Code Quality

it is very poor style to alter the input data in a map

Can you explain the reason behind this to me? I have never seen $_ localized inside of a map. I don't see why it's so bad to modify $_ inside the map. Unless you're maping through a list of references in which case you'd be modifying the original structure. I must admit to never having seen localized $_ in a map and that I've seen a million scripts that mangle $_ to death in such cases.

  • Comment on Re^2: Balancing Coding Time And Code Quality

Replies are listed 'Best First'.
Re: Re^2: Balancing Coding Time And Code Quality
by hardburn (Abbot) on Dec 04, 2003 at 15:01 UTC

    The Blue Camel has this to say about map on page 741:

    Because $_ is an alias (implicit reference) into the list's values, this variable can be used to modify the elements of the array.

    So you'll be modifying the orginal value, weather it was a list of references or not. Mearly chomping the value, as the code posted does, is unlikely to do real harm, so I wouldn't consider it a problem in this case.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

      Aha, I didn't realize that $_ was an alias within a map (greps as well then). Which makes a lot of sense if you take even half a second to think about it. I even threw together an example to prove it to myself.

      # because $_ is an alias, @foo is also modified my @foo = qw/one two three four five six/; my @bar = map { s/[aeiou]//g; $_ } @foo; print join(', ', @foo), $/; # because we localize $_, @foo is not modified my @foo = qw/one two three four five six/; my @bar = map { local $_ = $_; s/[aeiou]//g; $_ } @foo; print join(', ', @foo), $/; # not to mention even when you loop through an array my @foo = qw/one two three four five six/; s/[aeiou]//g for @foo; print join(', ', @foo), $/;

      I thought that was common knowledge; guess not...

      In any case, if the input list will not be used again after the map, i see no reason to create a local copy of $_.