在数组perl中推送数组

时间:2012-10-30 06:10:39

标签: arrays perl multidimensional-array

编辑:

如何将@myarr推入$ menu(见下文)

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 ]
     ];

2 个答案:

答案 0 :(得分:6)

这取决于你想要做什么。

您可以直接推送数组:

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" ]
];

导致myarr 元素被推送到menu,或者推送引用:

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

实际上是推送数组(嵌套数组)。

答案 1 :(得分:4)

你可以推它:

 use Data::Dumper;
 push (@$menu, @myarr);
 print Dumper($menu), "\n";