pushing array inside array perl

15,343

Solution 1

This depends on what exactly you want to do.

You can either directly push the array:

push (@$menu, @myarr);

#results in:

[
     "List",
     ["itemone", \&ds2],
     ["itemtwo", \&ds2],
     ["itemthree", \&ds2],
     ["itemfour", \&ds2],
     [ "Do Something (second)", \&ds2 ],
     [ "itemone", "itemoneb", "itemonec" ],
     [ "itemtwo", "itemtwob", "itemtwoc" ],
     [ "itemthree", "itemthewwb", "itemthreec" ],
     [ "itemfour", "itemfourb", "itemfourc" ]
];

which results in the myarr elements being pushed to menu, or push the reference:

push (@$menu, \@myarr);

#results in:

[
     "List",
     ["itemone", \&ds2],
     ["itemtwo", \&ds2],
     ["itemthree", \&ds2],
     ["itemfour", \&ds2],
     [ "Do Something (second)", \&ds2 ],
     [
        [ "itemone", "itemoneb", "itemonec" ],
        [ "itemtwo", "itemtwob", "itemtwoc" ],
        [ "itemthree", "itemthewwb", "itemthreec" ],
        [ "itemfour", "itemfourb", "itemfourc" ],
     ],
];

which actually pushes the array (nested array).

Solution 2

You can just push it:

 use Data::Dumper;
 push (@$menu, @myarr);
 print Dumper($menu), "\n";
Share:
15,343
user391986
Author by

user391986

Updated on June 11, 2022

Comments

  • user391986
    user391986 almost 2 years

    edited:

    How can I push @myarr into $menu (see below)

    my @myarr = (
                    [ "itemone", "itemoneb", "itemonec" ],
                    [ "itemtwo", "itemtwob", "itemtwoc" ],
                    [ "itemthree", "itemthewwb", "itemthreec" ],
                    [ "itemfour", "itemfourb", "itemfourc" ]
                   );
    
    $menu = [
             "List",
             ["itemone", \&ds2],
             ["itemtwo", \&ds2],
             ["itemthree", \&ds2],
             ["itemfour", \&ds2],
             [ "Do Something (second)", \&ds2 ]
         ];
    
  • tuxuday
    tuxuday over 11 years
    this pushes elements of @myarr into @$menu, to push an array push its reference push $@menu,\@myarr