Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

(take two...) Re: A split ing headache

by mwp (Hermit)
on Dec 12, 2000 at 12:28 UTC ( [id://46234]=note: print w/replies, xml ) Need Help??


in reply to A split ing headache

As my esteemed colleagues have pointed out, the LIMIT argument for split doesn't truncate tokens whose indices are greater than LIMIT, merely lumps them together as the last return value. Think of it like this: split EXPR on PATTERN into a list LIMIT elements long.
my $string = 'see:how:they:code'; my($zeroth, $first, $remainder) = split ':', $string, 3; print $zeroth, "\n", # see $first, "\n", # how $remainder, "\n"; # they:code

If you want to actually truncate the leftover list elements, try this:</o>

my($zeroth, $first, $second) = (split ':', $string)[0..2]; print $zeroth, "\n", # see $first, "\n", # how $second, "\n"; # they

And 'code' just goes away. Just watch your parens, because this is wrong:

split(':', $string)[0..2]

Hopefully you can see why.

Replies are listed 'Best First'.
Re: (take two...) Re: A split ing headache
by extremely (Priest) on Dec 12, 2000 at 14:19 UTC
    I tend to use alakaboo's construct when doing this: my (@bits) = (split /:/, $thing,4)[0..2] well, except that I constrain it to one more than the slice size so it doesn't do extra work.

    When assigning to a list of scalars I use: my ($a, $b, $c) = split /:/, $thing, 4; knowing that the last item with all the unsplit bits will just blow away. No reason to promote a list to an anonymous array when you don't have to. Not a big deal tho but I've always felt that asking for 4 parts and only saving 3 made more sense.

    --
    $you = new YOU;
    honk() if $you->love(perl)

      Perl does that for automagically. split() knows how many scalars (if a finite number) you had on the left-hand side of the function call, so it will optimize itself thus.

      japhy -- Perl and Regex Hacker
        You can put perl5 on my system but you can't get perl4 outta my head =) Ahh well, it USED to be a good idea...

        --
        $you = new YOU;
        honk() if $you->love(perl)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-20 01:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found