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

Hey Monks, I have a simple question, i really do not know, how to write it down. I have an Array
@array1 = (1,2,3,4,5);
and I want the first two elements (1 and 2) use in another Array.
@array2 = (1,2);
How do I do this? With grep? With splice? with push?? Thanks for your help

Replies are listed 'Best First'.
Re: How to push the first two elements of an array in another array
by choroba (Cardinal) on Sep 16, 2014 at 09:31 UTC
    Do you want to remove the elements from the first array? If yes:
    @array2 = splice @array1, 0, 2; # OR push @array2, shift @array1 for 1, 2; # OR ...

    If no:

    @array2 = @array1[0, 1]; # OR $array2[$_] = $array1[$_] for 0, 1; # OR ...

    I'd use the first alternative in both cases.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: How to push the first two elements of an array in another array
by AnomalousMonk (Archbishop) on Sep 16, 2014 at 09:31 UTC
    c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my @array1 = (1,2,3,4,5); my @array2 = @array1[ 0, 1 ]; dd \@array2; " [1, 2]

    Update:

    ... I want the first two elements (1 and 2) ...
    BTW: Perl arrays are (by default) 0-based, so the first two elements are at indices 0 and 1.

Re: How to push the first two elements of an array in another array
by Anonymous Monk on Sep 16, 2014 at 09:29 UTC

    How do I do this? With grep? With splice? with push?? Thanks for your help

    Have you read grep, splice, push?