in reply to How to differentiate hash reference and object reference?

Check out the ref function: (see perldoc -f ref)
#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my $foo = {}; bless($foo, "SOMECLASS"); #Comment this line out. my $type = ref $foo; print $type, "\n";

davis
Kids, you tried your hardest, and you failed miserably. The lesson is: Never try.

Replies are listed 'Best First'.
Re^2: How to differentiate hash reference and object reference?
by chromatic (Archbishop) on Aug 31, 2005 at 17:25 UTC

    No, don't do that. ref is broken:

    • It fails for certain valid invocants (class names).
    • It prohibits polymorphism, both in inheritance and interface equivalence.
    • It returns undef on failure, so you have to go through contortions to avoid undefined value warnings.
    • It's trivially easy to fool by blessing into a package named HASH.

    perlfunc in bleadperl recommends several other techniques for doing the same thing without the problems.

      You can also fool ref() by blessing your objects into the "\0" package. In that case, you'd get a false value on something that is not only a ref but is even blessed.
      Oh, didn't know that. Thanks!

      davis
      Kids, you tried your hardest, and you failed miserably. The lesson is: Never try.