Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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'


Comment on Re: Odd workings of split
Select or Download Code
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-09-22 21:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (202 votes), past polls