@alpha = qw/a b c d/; @beta = qw/e f/; $arr[0] = @alpha; $arr[1] = @beta;I want to, for example, determine the number of elements in the array $arr[0]. Thanks
use Data::Dumper;
@alpha = qw/a b c d/;
@beta = qw/e f/;
$arr[0] = \@alpha;
$arr[1] = \@beta;
print Dumper(@arr);
print scalar @{$arr[0]};
You have to pay attention to the sigils to understand why your method isn't working as you hoped. If the variable entity starts with a $ sigil, it's a scalar container. If it starts with a @ sigil, it's an array (a list container). A scalar container cannot hold a list. That means that the following statement behaves as follows:
$arr[0] = @alpha;
Behavior: Look at the container on the left hand side of the = operator. It's a scalar. That means that the right-hand side of the statement is evaluated in scalar context. An array, evaluated in scalar context doesn't return its contents, but rather, returns the number of elements it contains.
What you want, instead, is to put a reference (which is itself a scalar value) to the array into the scalar container '$arr[0]'. You can do that like this:
$arr[0] = \@alpha;
That puts a "pointer" or more appropriately described as a "reference" to @alpha into @arr[0]
In many situations you might prefer to hold a reference to a copy of @alpha's contents instead of a reference to @alpha itself. You can do that like this:
$arr[0] = [ @alpha ];
And in the name of not typing $arr[0], $arr[1], $arr[2], and so on, you can also do something a little cunning like this:
foreach( \@alpha, \@beta ) {
push @arr, $_;
}
...or for a copy instead of a direct reference...
foreach( [ @alpha ], [ @beta ] ) {
push @arr, $_;
}
See [doc://perlref], [doc://perlreftut], and [doc://perllol] for a much better explanation than I can give.
Dave
my @arr = (0,1,2);
my @nested = (3,4,\@arr);
print $#{$nested[2]};
Or also due to the same Perl oddness OP could:
my @arr = (0,1,2);
my @nested = (3,4,\@arr);
print scalar @{$nested[2]};
Prints:
3
perlmonks.org content © perlmonks.org and davido, GrandFather, Ido, lima1, scuffell, TedPride
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03