问题
What does this mean in Perl?
if (@array)if (!@array)
Does this mean if we ask Perl to check if array exists or not?
Thanks
回答1:
An array in scalar context returns the number of elements. So the if(@array) checks if the array has any elements or not. It's similar to if(scalar(@array)!=0).
回答2:
In Perl, an array in scalar context evaluates to the number of elements in the array. So
my @array = ('a', 'b');
my $n = @array;
sets $n to 2.
Also, if applies a scalar context to its parameter. So
my @array = ('a', 'b');
if (@array) { ...
is the same as
if (2) { ...
and, because 2 is considered true, the body of the if will get executed.
Finally, the only number that Perl considers to be false is zero, so if you pass an empty array
my @array = ();
if (@array) { ...
it is the same as
if (0) { ...
and the body of the if won't get executed.
There is no way of discovering whether a variable exists in Perl. As long as you use strict, which you always should, Perl won't let you run a program that refers to non-existent variables.
回答3:
if(@array) will be true if @array has at least one element.
my @array;
if (!@array) { print "empty array\n"; }
push @array, 11;
if (@array) { print "array has at least one element\n"; }
来源:https://stackoverflow.com/questions/19369145/what-does-if-array-mean-in-perl