The thing to realize about the @Data + 0; statement in your reply above is that it forces the evaluation of @Data in scalar context (yielding the number of elements) and then throws away the result!
All of these statements are equivalent:
my $n = 0 + @Data;
my $n = scalar @Data;
my $n = @Data;
In the first two, the scalar operation and the use of the scalar built-in on the right hand side of the assignment are redundant because the scalar assignment itself supplies all the scalar context that is necessary. (The usage
my $n = scalar @Data;
is sometimes advanced as a best practice for reasons of maintainability: supposedly, it makes crystal clear your intention to get the number of elements of the array.)
Where forcing scalar context through a null scalar operation or the use of scalar can be useful is in a situation in which the overall context is list, such as in the argument list of the print built-in:
c:\@Work\Perl>perl -wMstrict -le "my @Data = qw(foo bar baz); ;; print 'hoo ', @Data, ' ha'; print 'fee ', 0 + @Data, ' fie'; print 'hic ', scalar @Data, ' hoc'; " hoo foobarbaz ha fee 3 fie hic 3 hoc
Give a man a fish: <%-{-{-{-<
In reply to Re^4: Count elements in array ref
by AnomalousMonk
in thread Count elements in array ref
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |