eWebProgrammer
Distributednetworks GofPatterns
prev prev
  Course navigation
    Array subscript in Perl
The scalar operator in Perl
Notice the use of the scalar operator:
for($i = 0; $i <  scalar @bestpix; $i++) 
{
  print "$bestpix[$i]\n" 
}
The value of an array in scalar context is the number of elements in the array. So the value of scalar @bestpix is the number of elements in the @bestpix array.
In Perl, the type of an expression is often taken from the context, rather than a fixed set of rules. In cases where the context may be ambiguous, or give you a type that you don't expect, you can use the scalar operator to force an expression to a scalar context.

For example, this expression:
will print all the lines from the standard input (usually the keyboard) and then finish. But what if you only want to print one line? You could use an intermediate variable like this:
Or, you could use the scalar operator to force the context to a scalar and avoid the intermediate variable altogether: The scalar operator forces the context to be scalar, instead of the default list context for the print function call.
  Course navigation