Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does if (@array) mean in perl?

Tags:

scripting

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

like image 475
CBR Avatar asked Oct 14 '13 20:10

CBR


2 Answers

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

like image 126
psxls Avatar answered Oct 16 '22 03:10

psxls


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.

like image 24
Borodin Avatar answered Oct 16 '22 03:10

Borodin