Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: Odd workings of split

by tobyink (Abbot)
on Mar 29, 2012 at 13:42 UTC ( #962400=note: print w/replies, xml ) Need Help??

in reply to Odd workings of split

Your question has already been answered, but I'd like to point out that this:

$cmd[$_] = [split "\n", $cmd[$_]]->[0];

Might be better as:

$cmd[$_] = [split "\n", $cmd[$_], 2]->[0];

Setting the third parameter to "2" indicates that you don't want split to return any more than 2 items. So if your string is, say, 8 lines long, split will return a list containing two strings: the first line, then all the other lines. This saves Perl a bit of work splitting up a portion of the string that you're uninterested in.

Alternatively, if you use list assignment, like this:

($cmd[$_]) = split "\n", $cmd[$_];

... then Perl is actually smart enough to figure out the ",2" itself. Take a peek at:

perl -MO=Deparse -e'($cmd[$_]) = split "\n", $cmd[$_];'
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Odd workings of split
by Ralesk (Pilgrim) on Mar 29, 2012 at 15:24 UTC

    Yeah, had the limit argument in mind, but forgot to type it in. Good call.

    And itís nice to know Perl is smart enough to optimise things out like that!

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2016-10-23 12:40 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (301 votes). Check out past polls.