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
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)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With