Can you create an array of arraynames and then print the array contents ?

P

paul.porcelli

Hi there,
suppose I create an array of arryanames
@testarr=qw/@arr1 @arr2 @arr3/;

The I assign values to those arrays
@arr1=`ls /tmp`;
@arr2=`ls /var`;

Now I want to loop and print the first value in each array
foreach $val (@testarr) {
print $val[0];
}

The above does not work.
Is there another way this can be done ?

Many thanks.
 
M

Miroslav Suchy

Hi there,
suppose I create an array of arryanames
@testarr=qw/@arr1 @arr2 @arr3/;

The I assign values to those arrays
@arr1=`ls /tmp`;
@arr2=`ls /var`;

Now I want to loop and print the first value in each array
foreach $val (@testarr) {
print $val[0];
}

The above does not work.
Is there another way this can be done ?

Yes:


@testarr=qw/arr1 arr2 arr3/;

@arr1=`ls /tmp`;
@arr2=`ls /var`;

foreach $val (@testarr) {
print ${$val}[0];
}


Miroslav Suchy
 
J

John W. Krahn

suppose I create an array of arryanames
@testarr=qw/@arr1 @arr2 @arr3/;

The I assign values to those arrays
@arr1=`ls /tmp`;
@arr2=`ls /var`;

Now I want to loop and print the first value in each array
foreach $val (@testarr) {
print $val[0];
}

The above does not work.
Is there another way this can be done ?

Sure.

my @testarr;

for my $dir ( '/tmp', '/var' ) {
opendir my $dh, $dir or die "Cannot open $dir: $!";
push @testarr, [ grep !/^\./, readdir $dh ];
}

for my $val ( @testarr ) {
print map "$_\n", @$val;
}



John
 
D

Dave Weaver

Miroslav Suchy said:
@testarr=qw/arr1 arr2 arr3/;

@arr1=`ls /tmp`;
@arr2=`ls /var`;

foreach $val (@testarr) {
print ${$val}[0];
}

Symbolic references are fraught with danger.
It's much safer to use hard references instead:

#!/usr/bin/perl
use strict;
use warnings;

my @arr1=`ls /tmp`;
my @arr2=`ls /var`;

my @testarr = ( \@arr1, \@arr2 );

foreach my $array (@testarr) {
print $array->[0];
}


Or, if you need access to the names of the arrays themselves, in
addition to the values within, use that most handy of Perl
constructs, a hash:

#!/usr/bin/perl
use strict;
use warnings;

my @arr1=`ls /tmp`;
my @arr2=`ls /var`;

my %arrays = (
arr1 => \@arr1,
arr2 => \@arr2,
);

foreach my $array_name (keys %arrays) {
print "1st element in $array_name is $arrays{$array_name}[0]";
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,836
Latest member
BuyBlissBitesCBD

Latest Threads

Top