문제

In Perl, if you will assign an array to a scalar, you will get length of that array.

Example:

my @arr = (1,2,3,4);
my $x = @arr;

Now if you check the content of $x, you will find that $x contains the length of @arr array.

I want to know the reason why Perl does so. What is the reason behind it? I try at my level but could not find any good reason. So, can someone help me understand the reason behind the scene which is taking place?

도움이 되었습니까?

해결책

Perl uses contexts where other languages use functions to get some info or convert the value between different types. The concept of context is thoroughly explained in perldata manual page (man perldata).

In Perl, the same data look differently under different context. An array looks like a list of its elements in list context, while it looks like number of its elements in scalar context.

How else could it possibly look in scalar context?

  • It could be the fist element of the array. This can be done with my ($x) = @arr; or my $x = shift @arr; or my $x = $arr[0];.
  • It could be the last element of the array. This can be done with my ($x) = reverse @arr; or my $x = pop @arr; or my $x = $arr[-1];.

I cannot think of any other reasonable way to make a scalar from an array. Obviously using array length as its scalar value is better than these two, because it is somewhat global property of the array, while these two are fairly local. And it is also very logical when you look at typical use of array in scalar context:

die "Not enough arguments" if @ARGV < 5;

You can read < quite naturally as “is smaller than”.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top