in reply to How to find size of array in array?
Your line of code to find the length:
works because an array evaluates to the number of elements it contains in a scalar context. Assigning to a scalar (as you do above) provides a scalar context to the right hand side (RHS). So the array is evaluated in this scalar context, giving the length, which the assignment then puts into your '$asize' variable.$asize = @a;
Why did I bother spelling this out in a long-winded way? Because it is useful to understand what it going on. For example, I usually write the above as:
The 'scalar' keyword supplies a scalar context to its argument and gives the result of the evaluation. It is redundant in the above example (because we already have a scalar context from the assignment to the scalar).my $asize = scalar @a;
So why do I write it like that? Because:
I *need* to use the scalar keyword here, because otherwise the 'print' command gives a list context to the array, which lists all the elements instead of giving the size.#!/usr/local/bin/perl -w use strict; my @array = qw( 1 2 3 4 5 ); my $asize = scalar @array; print "Array size 1 is ", $asize, "\n"; print "Array size 2 is ", @array, "\n"; print "Array size 3 is ", scalar @array, "\n";
Since I sometimes get cut-and-paste happy, it is nice to have code which is explicit about what context it wants.