Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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

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 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.

Re: Append array to array of arrays
by LanX (Chancellor) 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)

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (13)
As of 2017-03-23 09:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (285 votes). Check out past polls.