The number of values in a list can only be determined by iterating over its values, or converting it to an array. Assigning it to a scalar won’t return the items count:
my $n = ('a', 'b', 'c'); # $n = 'c'
There’s an “empty parentheses” idiom, that can be used to get the number of elements:
my $n = () = ('a', 'b', 'c'); # $n = 3
Is it equivalent internally to
my $n = @{[ 'a', 'b', 'c' ]};
?
This is an interesting implementation detail: Does the assignment to an empty list create an (unnecessary) anonymous array?
There are two ways of answering this question: First, The Right Way: Try to figure out how this might be handled in the source. Is there a special case for assignment to an empty list evaluated in scalar context?
Being the lazy and ignorant type, I chose to use Benchmark:
I ran the benchmark a bunch of times, and the assignment to empty list had a slight advantage in all cases. If the difference were purely random, the probability of observing 10 timings all in favor of goatse is less than 0.1%, so I am assuming there is some kind of short circuit.
On the other hand, as running the benchmark @daotoad posted in the comments, probably gives a more complete picture:
Typical results on my machine (Windows XP Pro SP3, Core 2 Duo, 2 Gb memory, ActiveState
perl5.10.1.1006):And, with:
the results are:
Conclusion:
If in doubt, use
my $n = () = ...;