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

Hi

I want to use split to assign variables but keep the remainder and assign it to the last variable. And yes regular expression can do this I am aware, I was more interested if there is some way todo it using split.

my $string = "a b c d e f"; my ($e1, $e2, $e3) = split /\s/, $string;
The result currently would be:
e1 = a e2 = b e3 = c

What I want to do is for the remaining part to get assigned to e3 like.

e3 = c d e f

Replies are listed 'Best First'.
Re: Howto get last items using split
by mje (Curate) on Oct 21, 2009 at 08:36 UTC
    my ($e1, $e2, $e3) = split /\s/, $string, 3;

      Thanks it works gr8.

      But I think the proper response should have been RTFM, now that I saw the solution :D

        ... I think the proper response should have been RTFM ...
        Indeed, and for the benefit of those following along at home, the FM in question is split, with particular attention paid to the  LIMIT parameter.
        (See also  perldoc -f split from your consoles.)
Re: Howto get last items using split
by CountZero (Bishop) on Oct 21, 2009 at 16:33 UTC
    Another slightly different solution is to have as the last element in the list of variables to be stuffed with the split elements, an array. This will then collect all the last elements not stored in the previous variables. Thus you have all the "unused" elements together, nicely separated, ready to be used as and when necessary.
    my ($e1, $e2, @e3) = split /\s/, $string;

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James