Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Splitting on tabs then removing extra white space with map

by ikegami (Patriarch)
on Sep 18, 2007 at 04:16 UTC ( [id://639544]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://639544]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (8)
As of 2024-04-23 09:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found