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

Okay, I have an extremely foolish question on the uses of split. I have a string, lets call it $string. $string contains words seperated by an indeterminate amount of whitespace. I need to grab a few values out of the array like so

($valone, $valtwo, $valthree) = split( some regex, $string);

Currently I am using the regex /\s+/g. But this doesn't seem to work. $valthree gets what should be in $valtwo, $valtwo what should be in $valone, and $valone is left blank. I know that $string may or may not have leading whitespace.

If anyone could point out what I am doing wrong, it would be appreciated.

JAsomewhatembarrassedPH

Replies are listed 'Best First'.
Re: uses of split
by jptxs (Curate) on Nov 02, 2000 at 00:17 UTC

    well, i don't see mention of why you couldn't pre-process the data (I also don't see code for that matter : ), but what you could do is strip off the starting space and trailing space first and then feed it to split. You may also want to note that you don't need the /g in the regex for split.

    use strict; my $string = ' this that other '; $string =~ s/^\s+//; $string =~ s/\s+$//; my ($one, $two, $three) = split /\s+/, $string; print "$one\n$two\n$three\n\n";
    which then does:
    /home/jptxs > perl -w stripNsplit this that other /home/jptxs >

    "sometimes when you make a request for the head you don't
    want the big, fat body...don't you go snickering."
                                             -- Nathan Torkington UoP2K a.k.a gnat

(tye)Re: uses of split
by tye (Sage) on Nov 02, 2000 at 00:39 UTC

    That is what split " " is for. See "perldoc -f split" for more info.

            - tye (but my friends call me "Tye")
(jeffa) Re: uses of split
by jeffa (Bishop) on Nov 02, 2000 at 00:16 UTC
    Since $string may have leading whitespace, try removing it before the split:
    $string =~ s/^\s*//g;
    Otherwise, we'll need to see some more code to further understand the problem.