ref returns the base type that an object is, but not a package/object-type.
Reread docs :) . For blessed variables ref returns package into which variable is blessed.
Normally one uses ref with objects to check if they belong to some specific class and UNIVERSAL::isa with objects to check if they belong to some class or its subclass.
--
Ilya Martynov
(http://martynov.org/)
| [reply] |
Like IlyaM says, reread the docs. The examples at the ref link should explain the difference pretty much. In addition to the built in types, the functions also work for objects blessed into packages. Consider this example:
#!/usr/bin/perl -w
use strict;
# Our base, or super class
package Foo;
sub new
{
bless {}, shift;
}
# The subclass Bar inherits from Foo
package Bar;
use base 'Foo';
# The main package
package main;
# Instantiate an object of type Bar:
my $obj = Bar->new();
# Three different kinds of tests, to see what type the object is:
print "Using ref to test which object type:\n";
print "\$obj is Bar\n" if(ref $obj eq 'Bar');
print "\$obj is Foo\n" if(ref $obj eq 'Foo');
print "Using UNIVERSAL::isa:\n";
print "\$obj is Bar or subclass of Bar\n" if(UNIVERSAL::isa($obj,'Bar'
+));
print "\$obj is Foo or subclass of Foo\n" if(UNIVERSAL::isa($obj,'Foo'
+));
print "Using object method isa:\n";
print "\$obj is Bar or subclass of Bar\n" if($obj->isa('Bar'));
print "\$obj is Foo or subclass of Foo\n" if($obj->isa('Foo'));
As you see, ref will help you find out if an object is of type X, while isa will tell you if the object is of type X, or if the package inherits from X.
Hope that helps.
You have moved into a dark place.
It is pitch black. You are likely to be eaten by a grue. | [reply] [d/l] [select] |
Perhaps it is strange thinking, but I think that entry needs something more to it. Your example is quite better than the link. I do not know what it is, but the first time I read it, it does not seem clear, or rather, I thought it said one thing. I read it again, it seems to say something else, based on what people here have said. I should be able to get the proper meaning of what it says first time I read it.
(I will inspect it, to figure out how I read it wrong.)
| [reply] |