0

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

1
  • You really need to read perldoc perllol. Commented Feb 12, 2014 at 10:41

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.