in reply to PerlCritic, $_ and map

I never thought about these side effects and I'm glad I looked into this node. Each time I'm here I learn something new & valuable. Thanks to all of you!

But to say something in regards to the code example: Now that I know of the problems using this kind of trimming in map, what do you think about this alternative?

my @files = map { /^\s*(\S.*?)\s*$/ && $1 || "" } <$FILES>;

s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Replies are listed 'Best First'.
Re^2: PerlCritic, $_ and map
by ikegami (Patriarch) on Feb 12, 2009 at 23:00 UTC

    /^\s*(\S.*?)\s*$/ && $1 || ""
    is an odd way of writing
    /^\s*(\S.*?)\s*$/ ? $1 : ""

    If you remove the unnecessary \S, you get a pattern that always matches so
    /^\s*(.*?)\s*$/ ? $1 : ""
    can be simplified to
    /^\s*(.*?)\s*$/; $1

Re^2: PerlCritic, $_ and map
by JavaFan (Canon) on Feb 13, 2009 at 08:31 UTC
    what do you think about this alternative?
    my @files = map { /^\s*(\S.*?)\s*$/ && $1 || "" } <$FILES>;
    Quite bad actually. s/^\s+//; s/\s+$//; is common idiom enough that people instantly see what is being done (it is for instance mentioned in the perlfaq) - your solution requires more thinking to see what it does.

    And then there's performance.

    use Benchmark 'cmpthese'; our @data = ('foo', 'foo bar', ' foo', 'foo ', ' foo ', ' foo bar '); + cmpthese -1, { faq => 'for my $x (@::data) {$_ = $x; s/^\s+//; s/\s+$//}', Skeeve => 'for my $x (@::data) {$_ = $x; $_ = /^\s*(\S.*?)\s*$/ && $ +1 || ""}' }; __END__ Rate Skeeve faq Skeeve 19139/s -- -68% faq 59077/s 209% --

      While I agree about the benchmark result, I don't agree with what you call "Skeeve's". Try this:

      use Benchmark 'cmpthese'; our @data = ('foo', 'foo bar', ' foo', 'foo ', ' foo ', ' foo bar '); + cmpthese -1, { faq => 'my @f= map {local $_ = $_; s/^\s+//; s/\s+$//; $_ } @::da +ta', Skeeve => 'my @f= map { /^\s*(\S.*?)\s*$/ && $1 || "" } @::data', ikegami => 'my @f= map { /^\s*(.*?)\s*$/; $1; } @::data' }; __END__ Rate Skeeve ikegami faq Skeeve 24561/s -- -8% -28% ikegami 26614/s 8% -- -22% faq 33998/s 38% 28% --

      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e