in reply to Report on Blessing to 'tag' an object


Well, a side-effect I hadn't thought of before I tried it is that when blessing the array ref, it's no longer an 'ARRAY' and my switching on the value of ref breaks.

If necessary you could use UNIVERSAL::isa() to check if the blessed ref is an array ref:

#!/usr/bin/perl -wl use strict; my @a; my @b; my $a = \@a; my $b = \@b; print ref $a; print ref $b, "\n"; bless $a; print ref $a; print ref $b, "\n"; print 'ARRAY' if UNIVERSAL::isa($a, 'ARRAY'); print 'ARRAY' if UNIVERSAL::isa($b, 'ARRAY'); __END__ Prints: ARRAY ARRAY main ARRAY ARRAY ARRAY

--
John.

Replies are listed 'Best First'.
Re^2: Report on Blessing to 'tag' an object
by adrianh (Chancellor) on Jan 21, 2003 at 10:30 UTC
    If necessary you could use UNIVERSAL::isa() to check if the blessed ref is an array ref:

    isa won't always work:

    my $o = bless {}, 'ARRAY'; print "$o isa array" if UNIVERSAL::isa($o, 'ARRAY'); __END__ ARRAY=HASH(0x759c) isa array

    When you want to know your implementation type you want reftype from Scalar::Util.

    use Scalar::Util qw(reftype); my $hash_object = bless {}, 'ARRAY'; my $array_ref = [1,2,3]; my $array_object = bless [], 'Foo'; foreach ($hash_object, $array_ref, $array_object) { print "reftype of ", $_, " is ", reftype($_), "\n"; }; __END__ reftype of ARRAY=HASH(0x759c) is HASH reftype of ARRAY(0x7650) is ARRAY reftype of Foo=ARRAY(0x74b8) is ARRAY

      That won't always work:     Can't locate Scalar/Util.pm in @INC Which do you think is more likely? 1) That I blessed a non-array reference into the package named 'ARRAY' and I'll be upset that UNIVERSAL::isa() gets confused or 2) That I don't have Scalar::Util ?

      I think Scalar::Util has become "core" and so in a few years, the probabilities will shift. For now, I much prefer UNIVERSAL::isa() because I like my code to work on relatively old versions of Perl and I don't mind that it is possible to break my code by doing extremely stupid things. q-:

                      - tye

        Fair point :-)

        Scalar::Util has been core since 5.007003 for those interested.

        Personally, I prefer catch the weird cases - even if I have to install a few modules to do so.