Reputation: 1587
I have many short array
@seq1 /773..1447/ @seq2 /1 2 1843..1881 1923..2001/
but i use push
push(@add, @seq1);
push(@add, @seq2);
but it shows like it combine all array into one can't get each sub-array any more
/773..1447 1 2 1843..1881 1923..2001/
when i use
$number=@add;
it shows 6, but it should be 2. Can anyone explain the reason and how to change it.
When i use for loop to add each array
for(..){
@temp= split(/,/,$_);
push(@add, \@temp);
}
Then when i print @add; it only shows memory address, How can show all data in @add
Upvotes: 0
Views: 2579
Reputation: 954
the push
command takes an ARRAY and a LIST. It is important to understand what happens here.
The first argument must be an ARRAY, the one you want to push things on. After that it expects a LIST. What this means is that this push
statement provides list context to any @seq_n array - and sort of expands the array into separate elements. So all the elements of the @seq_n are being pushed onto your @add.
Since you did not want that to happen, you wanted an array that holds the separate lists - what we call in Perl a List-of-Lists - you actually wanted to push
a reference to your @seq_n arrays, using the \
character.
push @add, \@seq_1, \@seq_2, . . . \@seq_n;
Now you have an array that indeed holds references to each $seq_n.
To print them neatly, each sequence on its own line, you could iterate over each
foreach my $seq (@add) {
# $seq holds a reference to a list!
my $string = join " ", @$seq; # the @ dereferences the $seq
print $string, "\n";
}
but TIMTOWTDI
print map {(join " ", @$_), "\n"} @add;
Always consider the context in Perl, and try to embrace the charms of join, grep and map.
Upvotes: 1
Reputation: 50637
This is normal behavior, use reference to @seq1
if you want @add
to be two dimensional array,
push(@add, \@seq1);
To print all values in @add
you should use Data::Dumper; print Dumper \@add;
The reason is that all parameters get flattened into list when they are pushed into array, so
@a = @b = (1,2);
push(@add, @a, @b);
is same as writing
push(@add, $a[0],$a[1], $b[0],$b[1]);
Check perlref and perllol for reference.
Upvotes: 7