in reply to Re: On Scalar Context
in thread On Scalar Context
Most of the functions we're speaking in this node
(sort, keys, map, stat) just don't have mush sense in scalar sense.
I mean, perl is designed (?) so that you
can not get caught by calling a function in scalar context
when you'd mean a list context.
Suppose for example that you want to use stat.
You know what it does, so you expect an array from it.
As you want to use some specific entries of the array,
you won't write code like
$permissions= stat $filename; that just means
nothing. If you use something as a list, you
automatically call it in array context.
Compare this with the other way.
Calling a function that you expect to return one single value
IS a possible trap, for example,
you might accidentally write
and expect that localtime returns a timestamp like "Thu May 13 20:26:09 2004",
as it does in scalar context.
This kind of trap is really dangerous, I
think anyone learning Perl has fallen to it at least once.
(The most dangerous are operations that have entirely different side effects in different contexts, like /g regexps.)
warn "customer arrived at ", localtime;
So, returning to the list functions, some of
these have no meaning in scalar context (like sort, @arr[@inds],
map), and Perl typically gives a warning whe you use them that way.
Others are typically used in list context (grep, @array, stat, keys)
so you would only use them in scalar context
if you already expect some sort of behavior (that is,
you have read the manual).
Others are both used in list and scalar contexts equally often,
like readline, readdir, m//g, the comma operator,
the yadda-yadda operator; these really perform two different
things in the two contexts. Yes, you have to know this type,
but still, you won't probably get trapped by excepting something else as
a scalar value if you only know the list value, only
the other way round. (Well, maybe with m//g, yes.)