theboogwa
theboogwa

Reputation: 13

perl foreach array of arrays

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

Upvotes: 1

Views: 620

Answers (1)

DJG
DJG

Reputation: 6543

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.

Upvotes: 3

Related Questions