Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Odd workings of split

by moritz (Cardinal)
on Mar 29, 2012 at 12:49 UTC ( #962376=note: print w/ replies, xml ) Need Help??


in reply to Odd workings of split

A tiny correction: split doesn't return undef, it returns the empty list. Accessing [ (empty list) ]->[0] is what produces the undef.

The documentation of split also mentions this case:

Note that splitting an EXPR that evaluates to the empty string always returns the empty list, regardless of the LIMIT specified.

The problem is really that split is used for too many things, and it tries to cater to all needs.

A different way to approach this is not to ask what to split on, but ask what you want to extract. For example you can write

$cmd[0] = ($cmd[0] =~ /.*/g)[0]

where .* matches every character up to (but excluding) the first newline.

Or explicitly state what you want removed:

$cmd[0] =~ s/\n.*/s;

In Perl 6, split is less magical, and you are encouraged to write patterns that match what you're after (and not patterns that match the separator, so that still works):

$cmd[0].=comb(/\N*/);

I'm not sure what else to write, since you didn't really have a question :-)


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 13:03 UTC

    A tiny correction: split doesn't return undef, it returns the empty list. Accessing [ (empty list) ]->[0] is what produces the undef.

    Ahhhhhhhhhhhhhh, that makes sense! Thanks!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2014-12-27 08:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls