in reply to Splitting on tabs then removing extra white space with map

Since nobody mentioned it, the problem is that the return value of s/// isn't the modified string.

my @points = map { s/\s+//; $_ } split(/\t/, $_);

But then you're modifying map's arguments without intending to do so. Modifying $_ in map is a bad idea. (If you really do mean to modify map's arguments, using for would make your intent more obvious.)

my @points = map { local $_ = $_; s/\s+//; $_ } split(/\t/, $_);

Yuck! List::MoreUtils provides a function for just this purpose. It even uses a better method of localizing $_.

use List::MoreUtils qw( apply ); my @points = apply { s/\s+// } split(/\t/, $_);

Replies are listed 'Best First'.
Re^2: Splitting on tabs then removing extra white space with map
by c4onastick (Friar) on Sep 18, 2007 at 06:01 UTC

    Ah! Thank you! That makes much more sense. I tried every context permutation between map and split I could think of.

    Modifying $_ in map is a bad idea.

    I though this was one of map's strengths? Am I mistaken?

      In what situation would it be a strength? map is usually used as
      my @new = map { ... } @old;

      By changing $_, you *also* change @old in non-obvious manner.