Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Append array to array of arrays

by Anonymous Monk
on Jun 28, 2013 at 00:31 UTC ( #1041119=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks
I was wondering, is there a way to append an array to an already existing array of arrays, BUT, to put this new array in the beggining?
For instance, say you have the @AoA:
@AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], );
How can you add the array:
@new_arr = ("pebbles", "bamm bamm", "dino");
so that, in the end, you have:
@AoA = ( ["pebbles", "bamm bamm", "dino"], [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], );

Replies are listed 'Best First'.
Re: Append array to array of arrays
by roboticus (Chancellor) on Jun 28, 2013 at 02:13 UTC

    There are multiple ways to do so, here are three:

    $ cat use strict; use warnings; use Data::Dumper; my @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], ); # Add to beginning of array unshift @AoA, [ "pebbles", "bamm bamm", "dino" ]; # Splice into beginning of array splice @AoA, 0, 0, [ "Fred", "Velma", "Shaggy", "Scooby" ]; # Rebuild with new entry at beginning @AoA = ( [ "Bugs", "Daffy" ], @AoA ); print Dumper(\@AoA); $ perl $VAR1 = [ [ 'Bugs', 'Daffy' ], [ 'Fred', 'Velma', 'Shaggy', 'Scooby' ], [ 'pebbles', 'bamm bamm', 'dino' ], [ 'fred', 'barney' ], [ 'george', 'jane', 'elroy' ], [ 'homer', 'marge', 'bart' ] ];


    When your only tool is a hammer, all problems look like your thumb.

Re: Append array to array of arrays
by LanX (Bishop) on Jun 28, 2013 at 00:42 UTC
    see unshift


    DB<106> unshift @AoA, \@new_arr => 4 DB<107> \@AoA => [ ["pebbles", "bamm bamm", "dino"], ["fred", "barney"], ["george", "jane", "elroy"], ["homer", "marge", "bart"], ] DB<108> unshift @AoA, [qw/ directly as literal/] => 5 DB<109> \@AoA => [ ["directly", "as", "literal"], ["pebbles", "bamm bamm", "dino"], ["fred", "barney"], ["george", "jane", "elroy"], ["homer", "marge", "bart"], ]
    HTH! =)

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1041119]
Approved by davido
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (2)
As of 2018-05-26 01:08 GMT
Find Nodes?
    Voting Booth?