scalar
scalar EXPRThis pseudofunction may be used within a
LIST to force EXPR
to be evaluated in scalar context when evaluation in list context would
produce a different result. For example:
my($nextvar) = scalar <STDIN>;
prevents <STDIN> from
reading all the lines from standard input before doing the assignment,
since assignment to a list (even a my
list) provides list context. Without the scalar in this example, the first line from
<STDIN> would still be assigned
to $nextvar, but subsequent lines
would be read and thrown away, since the list we’re assigning to is only
able to receive a single scalar value.
Of course, a simpler, less-cluttered way would be to just leave the parentheses off, thereby changing the list context to a scalar one:
my $nextvar = <STDIN>;
Since a say function is a
LIST operator, you have to say:
say "Length is ", scalar(@ARRAY);
if you want the length of @ARRAY to be printed out.
There’s no “list” function
corresponding to scalar since, in
practice, one never needs to force evaluation in list context. That’s
because any operation that wants LIST already
provides list context to its list arguments for free.
Because scalar is a unary
operator, if you accidentally use a parenthesized list for the
EXPR, this behaves as a scalar comma
expression, evaluating all but the last element in void context and
returning the final element evaluated in scalar context. This is seldom
what you want. The following single statement:
print uc(scalar(&foo,$bar)),$baz;
is the (im)moral ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access