cbrdy
cbrdy

Reputation: 812

What does if (@array) mean in perl?

What does this mean in Perl?

  1. if (@array)
  2. if (!@array)

Does this mean if we ask Perl to check if array exists or not?

Thanks

Upvotes: 6

Views: 5397

Answers (3)

psxls
psxls

Reputation: 6925

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).

Upvotes: 13

Borodin
Borodin

Reputation: 126722

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.

Upvotes: 11

mpapec
mpapec

Reputation: 50637

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"; }

Upvotes: 5

Related Questions