Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, This is a little trival question but would prove useful. When use split, i often declare every single point split. But if i was interested in the 4th split how can i do this quickly? e.g split the following, but i just want to declare $x = 4th This summer is very cold compared to last i.e "very" i would use
($one, $two, $three, $four, $five, $six, $seven, $eight) = split (/\s+ +/, $_);

Replies are listed 'Best First'.
Re: another split question
by tinita (Parson) on Jul 19, 2004 at 10:35 UTC
    my $four = (split /\s+/, $_, 5)[3];
    the 5 just says split not to bother with more than 5 elements, so the rest of the string (beginning with the 5th element) won't be splitted. then this: (...)[3] is a list slice which takes the 4th element of the list.
Re: another split question
by reneeb (Chaplain) on Jul 19, 2004 at 10:33 UTC
    my $fourth = (split(/ /,$string))[3];
Re: another split question
by pbeckingham (Parson) on Jul 19, 2004 at 13:04 UTC

    I have seen these variations:

    (undef, undef, undef, $four) = split /\s+/, $_, 5;
    and
    $four = (split /\s+/, $_, 5) [3];

Re: another split question
by Art_XIV (Hermit) on Jul 19, 2004 at 14:02 UTC

    split's default behavior will split on multiple whitespace, much like /\s+/, with the bonus of ignoring leading and trailing whitespace:

    use strict; use warnings; while (<DATA>) { print "The fourth element is ", (split)[3], "\n"; } __DATA__ one two three four five six seven A B C D E F G H I spam eggs spam spam and spam
    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"