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

I came across:
($a, $b, @rest) = split;
in Section 2.3.4 of the Camel book which discusses "List Values and Arrays". I'm pretty baffled by it. Can someone please explain this line of code?

Replies are listed 'Best First'.
Re: Split function in a list context
by THRAK (Monk) on Apr 13, 2001 at 17:12 UTC
    This code will split $_ on white space. So, if...
    $_ = "dog cat frog bird hamster"; ($a, $b, @rest) = split; # $a = "dog"; # $b = "cat"; # @rest = qw(frog bird hamster); # OR # rest[0] = "frog"; # rest[1] = "bird"; # rest[2] = "hamster";


    -THRAK
    www.polarlava.com
Re: Split function in a list context
by rchiav (Deacon) on Apr 13, 2001 at 17:07 UTC
    What part of this baffles you? The fact that they are omitting what to split? The fact that they are not providing a delimiter? Or how they are assigning the results of split?

    For the first, It's splitting what's in $_. If no delimiter is specified, it will split on whitespace. And as far as the assignment of the results, it's taking the first 2 elements of the return values and assigning them to $a and $b. Then, all the rest of the return values are put into the array @rest. This is the documentation for split

    Hope this helps..
    Rich

Re: Split function in a list context
by nysus (Parson) on Apr 13, 2001 at 17:02 UTC
    Let me clarify something. The reason I'm confused is that the split function has no arguments. Thanks.
      Haha, that's funny!

      splits $_ on whitespace
      Update: Also looks like it strips leading whitespace...
      Update2: I meant it was funny everyone answered question backwards... sheesh.
                      - Ant

        Update2: I meant it was funny everyone answered question backwards... sheesh.
        I hope you took that as valuable feedback about how you asked the question.

        Someone once told me that the meaning of any message is the effect it has on the recipient, regardless of the intent that the sender gave it originally. So, if everyone interpreted it as a comment on the left side of the equals, that was your message, and you shouldn't have been surprised at the result.

        Now, if that wasn't the message you intended, perhaps you could have been clearer in framing the question.

        -- Randal L. Schwartz, Perl hacker


        update: in case it's not clear, I'm addressing this to the original poster, not the person to whom I replied. {grin}