Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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" ], );
thanks

Comment on Append array to array of arrays
Select or Download Code
Re: Append array to array of arrays
by LanX (Canon) on Jun 28, 2013 at 00:42 UTC
    see unshift

    edit

    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)

Re: Append array to array of arrays
by roboticus (Canon) on Jun 28, 2013 at 02:13 UTC

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

    $ cat u.pl 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 u.pl $VAR1 = [ [ 'Bugs', 'Daffy' ], [ 'Fred', 'Velma', 'Shaggy', 'Scooby' ], [ 'pebbles', 'bamm bamm', 'dino' ], [ 'fred', 'barney' ], [ 'george', 'jane', 'elroy' ], [ 'homer', 'marge', 'bart' ] ];

    ...roboticus

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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1041119]
Approved by davido
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2014-08-21 21:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (143 votes), past polls