in reply to semantics differences, &ref and &UNIVERSAL::isa()

I don't know where to look for this in the docs, but isa handles inheritance, whereas ref does not. For example:
package A; sub new { my $c = shift; $c = ref $c || $c; bless {}, $c; } package B; @ISA=qw(A); sub new { my $c = shift; $c = ref $c || $c; bless {}, $c; } package main; my $b = new B; print "b isa A = ", $b->isa('A'), "\n"; print "ref b = ", ref($b), "\n";
/s

Replies are listed 'Best First'.
Re: Re: semantics differences, &ref and &UNIVERSAL::isa()
by Dog and Pony (Priest) on May 18, 2002 at 17:01 UTC
    ref (and isa) would be good places to look at for docs. :)
    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.

      the ref and isa docs still did not seem to help.. the only thing I reall got was:

      ref returns the base type that an object is, but not a package/object-type
      &UNIVERSAL::isa returns true or false is the first argument is an instance of of the package of the second argument...

      Now back to one of my other questions: when would I use either?

        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/)

        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.