See ref. And variables aren't blessed, referenced values (SV*, AV*, et al) are blessed (not the variable containing the reference or the reference itself; it's the thing that is blessed or not, not the pointer to the thing).
if ( ref($a) && ref($a) !~ /HASH|ARRAY/ ) {
$a->blabla(...) ;
}According to the answers to this post I assume this is the answer ?!
A better answer may be Scalar::Util and blessed.
$scalar = "foo"; $class = blessed $scalar; # undef $ref = []; $class = blessed $ref; # undef $obj = bless [], "Foo"; $class = blessed $obj; # "Foo"
-xdg
Code written by xdg and posted on PerlMonks is [http://creativecommons.org/licenses/publicdomain|public domain]. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
if ( ref($obj) eq "Foo" )
{
# We have a Foo object
}
Simple, sweet, and gets the job done. Why over engineer? Of course, if you were already using Scalar::Util for some of its other uses, then I'd say great, but to use a module for something as simple as this, is overcomplicating matters.
Because if you're merely interested in finding out if the reference is to an instance of some class (as opposed to a hashref, arrayref, ...), what do you put on the other side of the eq? Not to mention the problems with that if you want to gracefully handle subclasses (in which case you really want UNIVERSAL::isa()).
And ++ to xdg; I'd forgotten all about Scalar::Util::blessed. Much better answer than mine.
Thanks!
If you want to see some interesting complexity on what should be such a simple topic, see Why reftype and blessed are making my life harder than it needs to be.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
Because the question was how to tell if the reference was blessed, not how to tell if it was blessed into a specific package, ref won't tell you that unless you do a lot of && ref($obj) !~ /HASH/ && ref($obj) !~ /ARRAY/...
| We're not surrounded, we're in a target-rich environment! |
|---|
ref $varfoo bar
if ( ref($var) && $var->isa("Some::Package") )
{
$var->someMethod();
}
Or better yet:
my $sub;
if ( ref($var) && ($sub = $var->can("someMethod")) )
{
$sub->();
}
else
{
die "Method someMethod not found."
}
Of course you don't have to capture the return of "can" but it can be convenient.
eval { local $SIG{__DIE__}; $ref->isa('Some::Package'); }
You might trigger a die handler, which could be bad. For example, one of [cpan://Test::More]'s dependencies has one. See [id://532653] for more on the topic.
Example blessed => a direct hit, node 217784
perlmonks.org content © perlmonks.org and davidrw, dragonchild, Fletch, jasonk, jeanluca, linux454, monkfan, PodMaster, wfsp, xdg
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03