Reputation: 41
I have several arrays which have same size like below:
@m1= (1,1,0,1);
@m2= (0,1,1,1);
@m3= (0,1,1,0);
@m4= (1,1,0,0);
The question is how can I put it in one array like this?
@m = (
[1,1,0,1],
[0,1,1,1],
[0,1,1,0],
[1,1,0,0]
);
Upvotes: 3
Views: 90
Reputation: 23055
Edit: Since you want to copy the arrays (as per your comment), then I would do this--
my @m = ( [ @m1 ], [ @m2 ], [ @m3 ], [ @m4 ] );
See perldoc perlref and perldoc perlreftut for more information.
Original answer:
If you want to flatten them into one array:
my @m = ( @m1, @m2, @m3, @m4 );
If you want an array of arrayrefs:
my @m = ( \@m1, \@m2, \@m3, \@m4 );
Example:
use Data::Dumper;
my @m1= (1,1,0,1);
my @m2= (0,1,1,1);
my @m3= (0,1,1,0);
my @m4= (1,1,0,0);
my @m = ( @m1, @m2, @m3, @m4 );
warn Dumper( \@m );
my @m_again = ( \@m1, \@m2, \@m3, \@m4 );
warn Dumper( \@m_again );
Output:
$VAR1 = [
1,
1,
0,
1,
0,
1,
1,
1,
0,
1,
1,
0,
1,
1,
0,
0
];
$VAR1 = [
[
1,
1,
0,
1
],
[
0,
1,
1,
1
],
[
0,
1,
1,
0
],
[
1,
1,
0,
0
]
];
Upvotes: 7
Reputation: 385546
my @m = ( \@m1, \@m2, \@m3, \@m4 );
but you should probably have avoided putting them into separate arrays to begin with.
For example,
my @m1 = (1,1,0,1);
my @m2 = (0,1,1,1);
...
my @m = ( \@m1, \@m2, \@m3, \@m4 );
can be written as
my @m = (
[1,1,0,1],
[0,1,1,1],
...
);
For example,
my @m1 = f();
my @m2 = g();
...
my @m = ( \@m1, \@m2, \@m3, \@m4 );
can be written as
my @m;
$m[0] = [ f() ];
$m[1] = [ g() ];
...
or
my @m;
push @m, [ f() ];
push @m, [ g() ];
...
Upvotes: 0
Reputation: 67900
You would do either of these things:
push @m, \@m1, \@m2, ... # references, using the same memory address
push @m, [ @m1 ], [ @m2 ], .... # making copies, placing them in anonymous arrays
This will create a two-dimensional array, which is what you have described in your question and I assume you want. Of course, you don't need to use push
, but can use any way to manipulate an array.
Upvotes: 6