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 its 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]
[choroba]: BTW, both the bands I play in performed on Friday (at the same event). Quite an exhausting experience.
[Corion]: choroba: Ooof! I can imagine that ;)
[Corion]: I think at a Perl workshop some years ago I gave two talks on the same day and after that decided to only submit one talk per event ;)
[LanX]: you play the triangle, right?
[choroba]: just one of its angles, in fact
[LanX]: <|--
[choroba]: Reminds me of an old joke about an orchestra...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2017-03-27 11:44 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (319 votes). Check out past polls.