Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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]
[LanX]: aha Sandy Koufax is a Jewish hero because he didn't play on Jom Kippur, hence stonecolddevin's Sig is expressing Jewish "pride" ?
LanX atheism is so boring logical...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2017-05-24 21:30 GMT
Find Nodes?
    Voting Booth?