w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Array in scalar context in Perl

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

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.