Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Surprise: scalar(($x, $y) = split)

by JavaFan (Canon)
on Oct 28, 2011 at 14:55 UTC ( [id://934417]=note: print w/replies, xml ) Need Help??


in reply to Surprise: scalar(($x, $y) = split)

$ perl -e 'warn 0+(@x = split " ", "foo bar\n");' 2 at -e line 1. $ perl -e 'warn 0+(($x, $y) = split " ", "foo bar\n");' 3 at -e line 1. $
Note that there are *three* magical features happening. First there's the magic of the first argument; if the first argument of split is a pattern consisting of a single space, split splits on any whitespace. Which includes the newline. So, you actually have *3* fields, ("foo", "bar", "" -- the empty string following the newline), so it's the first case that's odd, not the second. It's the second magical feature that's to blame - in the absence of a limit, trailing empty fields are removed.

You wouldn't have been surprised if you had chomped your line.

Replies are listed 'Best First'.
Re^2: Surprise: scalar(($x, $y) = split)
by ambrus (Abbot) on Oct 28, 2011 at 15:24 UTC

    The other two magic might be confusing but they're not really necessary here. I can still write this and be surprised.

    $ perl -we '$n = () = split ",", "one,two,three,four,five"; print "I f +ound $n comma-separated words\n"' I found 1 comma-separated words $ perl -we '$n = ($x) = split ",", "one,two,three,four,five"; print "I + found $n comma-separated words, the first of which is $x\n"' I found 2 comma-separated words, the first of which is one

    And even if I chomp the line, there could be trailing spaces or carriage returns in the line that I expect split " " to cut off.

Re^2: Surprise: scalar(($x, $y) = split)
by hbm (Hermit) on Oct 28, 2011 at 15:26 UTC

    Adding to the confusion?

    $ perl -e 'warn 0+(($x, $y) = split/ /, "foo bar\n");' 2 at -e line 1. $ perl -e 'warn 0+(($x, $y) = split$", "foo bar\n");' 2 at -e line 1.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-24 10:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found