Given Example Code:
foo(bar=>"test");
foo(bar=>["test"]);
sub foo {
my $args = {@_};
say ref($args->{bar});
say ref(\$args->{bar});
}
Outputs:
{expected blank}
SCALAR
ARRAY
REF
What I would like to test for is the best way to check if what is passed is a scalar or an array. Something like:
given( ref($args->{bar}) ){
when "SCALAR" { }
when "ARRAY" { }
}
I could concatenate the two ref types and do a regex-when, but that’s inefficient. I could also test it like the following, but not sure if that’s preferred:
if ( ref(\$args->{bar}) eq "SCALAR" ) { ... }
elsif ( ref( $args->{bar}) eq "ARRAY" ) { ... }
else { return; }
You’re not trying to differentiate between a scalar and an array. You get a scalar in both cases. You’re trying to differentiate between a non-reference and a reference to an array.
or
or
or
or (assuming those are the only two types of values allowed)
(Note that Scalar::Util’s
reftypeactually gets the ref type.refcan return a class name instead of a reference type.)Note that differentiating values based on storage type is a poor design in Perl. It necessarily buggy, since it breaks overloaded objects.