How do I tell what type of value is in a Perl variable?
$x
might be a scalar, a ref to an array or a ref to a hash (or maybe other things).
How do I tell what type of value is in a Perl variable?
$x
might be a scalar, a ref to an array or a ref to a hash (or maybe other things).
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...
$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) . "
";
print "type of y: " . ref($y) . "
";
print "base type of x: " . reftype($x) . "
";
print "base type of y: " . reftype($y) . "
";
...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.
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.
I like polymorphism instead of manually checking for something:
use MooseX::Declare;
class Foo {
use MooseX::MultiMethods;
multi method foo (ArrayRef $arg){ say "arg is an array" }
multi method foo (HashRef $arg) { say "arg is a hash" }
multi method foo (Any $arg) { say "arg is something else" }
}
Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else
This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.
Your type library:
package MyApp::Types;
use MooseX::Types -declare => [ EvenNumberLessThan42 ];
use MooseX::Types::Moose qw(Num);
subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };
Then make Foo support this (in that class definition):
class Foo {
use MyApp::Types qw(EvenNumberLessThan42);
multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}
Then Foo->new->foo(40)
prints arg is an even number less than 42
instead of arg is something else
.
Maintainable.
At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref
or reftype
is a bad idea. I don t recall who put the idea forward, or the link. Sorry.
The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie
a filehandle so that it acts like a hash, the testing with reftype
will tell you that you have a filehanle. It won t tell you that you need to use it like a hash.
So, the argument went, it is better to use duck typing to find out what a variable is.
Instead of:
sub foo {
my $var = shift;
my $type = reftype $var;
my $result;
if( $type eq HASH ) {
$result = $var->{foo};
}
elsif( $type eq ARRAY ) {
$result = $var->[3];
}
else {
$result = foo ;
}
return $result;
}
You should do something like this:
sub foo {
my $var = shift;
my $type = reftype $var;
my $result;
eval {
$result = $var->{foo};
1; # guarantee a true result if code works.
}
or eval {
$result = $var->[3];
1;
}
or do {
$result = foo ;
}
return $result;
}
For the most part I don t actually do this, but in some cases I have. I m still making my mind up as to when this approach is appropriate. I thought I d throw the concept out for further discussion. I d love to see comments.
Update
I realized I should put forward my thoughts on this approach.
This method has the advantage of handling anything you throw at it.
It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat WTF .
I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.
I don t like this implementation.
I am building a Web interface to monitor an embedded system. I have built a Perl script which runs remote commands and gathers output from that system. Now what I need is a Web interface which makes ...
How do I tell what type of value is in a Perl variable? $x might be a scalar, a ref to an array or a ref to a hash (or maybe other things).
When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...
I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...
I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...
I would like to submit a form to a CGI script localy (w3c-markup-validator), but it is too slow using curl and apache, I want to use this CGI script more than 5,000 times in an another script. and ...
So I m running perl 5.10 on a core 2 duo macbook pro compiled with threading support: usethreads=define, useithreads=define. I ve got a simple script to read 4 gzipped files containing aroud 750000 ...
A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...