How to check if LVALUE represents SCALAR

For years, I am using a code that contains the following condition

ref \$_[0] eq 'SCALAR'

I always expect there an ARRAY or SCALAR, but recently I passed substr() into that parameter. Unexpected things happened. The condition returned a false value.

Then I figured it out. The ref returned LVALUE instead of SCALAR.

Since LVALUE is a weird type of reference, I need to check if a scalar is behind it.

How can I check is this LVALUE represents SCALAR or not?

>Solution :

An LVALUE is a special magical value that takes action when it is assigned to. So for example, calling f($hash{foo}) doesn’t immediately create the foo entry in %hash; instead a temporary LVALUE is created and passed to the sub as $_[0]. If $_[0] is subsequently assigned to, that value gets stored as $hash{foo}.

An LVALUE is a scalar (i.e. it holds a single value), just an odd type of scalar.

So it’s likely that the code can be fixed by just accepting both SCALAR and LVALUE as valid values. But it will depend on exactly why the check is done. It may also be that such a check is a logic error and is not actually needed, or is buggy. For example ref \$_[0] should never return ARRAY.

Leave a Reply