How do I tell what type of value is in a Perl variable?
ref():
Perl provides the
ref()
function so that you can check the reference type before dereferencing a reference...By using the
ref()
function you can protect program code that dereferences variables from producing errors when the wrong type of reference is used...
A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.
If you want to know if it is a reference, you can use ref
. If you want to know the reference type,
you can use the reftype
routine from Scalar::Util.
If you want to know if it is an object, you can use the blessed
routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL
has some methods to tell you about an object: if you want to check that it has the method you want to call, use can
; if you want to see that it inherits from something, use isa
; and if you want to see it the object handles a role, use DOES
.
If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied
. If you get an object, continue your checks.
If you want to know if it looks like a number, you can use looks_like_number
from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.
If you need to do something more fancy, you can use a module such as Params::Validate.
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.