What does if (@array) mean in perl?

Deadly 提交于 2019-12-13 14:36:29

问题


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


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!