Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Perl has two contexts in which expressions can be evaluated: scalar , and list. These contexts actually determine what the expression generates. It is recommended that the context be made explicit when an expression is evaluated in an unexpected context, that the context be made explicit. Implicit context switching makes programs difficult to read and more error prone.

...

The developer mistakenly left out the }} \ indicator when initializing {{$array_ref. Consequently, it contains not instead of a reference to the array, but rather it contains the number of elements in the array. When passed to the print_array() subroutine, this program prints an empty array.

...

Code Block
bgColor#ffcccc
langperl
my @array; # initialize
my $cardinality = @array;
print "The array has $cardinality elements\n";

While Although this program works correctly, there are less ambiguous ways to obtain the number of elements of an array can be obtained in less ambiguous ways.

Compliant Solution (scalar())

This compliant solution uses the scalar() builtin built-in subroutine to obtain the number of elements of an array.

Code Block
bgColor#ccccff
langperl
my $cardinality = scalar( @array);
print "The array has $cardinality elements\n";

This compliant solution again evaluates @array in scalar context just like as in the noncompliant code example. However, the scalar() makes this evaluation explicit, removing any doubt as to the programmer's intentions.

...