1

I have 7 arrays (@p1 @p2 @p3 @p4 @p5 @p6 @p7) and I want to want to push a value to each array, but I'm having trouble making it work. Below is an example of what I'm trying to do.

$something="some value";
@arrays=qw/@p1 @p2 @p3 @p4 @p5 @p6 @p7/;

foearch $line (@arrays) {
     push $line, $something;
     }
1
  • 4
    Be sure to always use use strict; use warnings; Commented Dec 1, 2014 at 3:54

1 Answer 1

3

The qw operator takes all the values between the delimiters and returns a list of strings of those values. So in your example:

@arrays=qw/@p1 @p2 @p3 @p4 @p5 @p6 @p7/;

actually sets @arrays to:

('@p1', '@p2', '@p3', '@p4', '@p5', '@p6', '@p7')

which is simply a list of strings.

What you want to do instead is to set @arrays to a list of references to your set of arrays. You can take a reference by preceding the sigil of a variable with a \.

So, change

@arrays = qw/@p1 @p2 @p3 @p4 @p5 @p6 @p7/;

to

@arrays = (\@p1, \@p2, \@p3, \@p4, \@p5, \@p6, \@p7);

By dereferencing each individual array reference in your loop, (which push does for you automatically in perl) you can push what you need into each original array.

See perlreftut for details on how array references work.

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

2 Comments

Mentioning for my $i (0..6) { push @{ $matrix[$i] }, $something; } seems necessary.
@arrays = \(@p1, @p2, @p3, @p4, @p5, @p6, @p7);

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.