develooper Front page | perl.perl6.language | Postings from January 2001

[]->isa('Foo') to not throw exceptions

From:
Piers Cawley
Date:
January 4, 2001 07:50
Subject:
[]->isa('Foo') to not throw exceptions
Message ID:
m2lmsrmien.fsf@rt158.private.realtime.co.uk
Did we do this one already?

I have an embarrassingly large amount of code that has to do C<eval {
$foo->isa('Foo') }>, or C<eval { $foo->can('Bar') }> because there is a
chance that C<$foo> is an unblessed reference.

I would use UNIVERSAL::can directly, but I have some code (a
container/decorator class) that messes with isa so that it can
masquerade as the thing it contains (which could be one of a number of
classes) without having to be subclassed. Using UNIVERSAL::can
directly in this case could be vaguely disastrous:

    sub can {
        my($self, $method) = @_;
        my $can = $self->SUPER::can($method);
        return $can if $can;
        $can = ref($self) && $self->contents->can($method);
        return unless $can;
        return sub {
            my $self = shift;
            return $can->($self->contents, @_);
        };
    }

    sub isa {
        my($self, $class) = @_;
        $self->SUPER::isa($class) || 
            $self->contents->isa($class);
    }

-- 
Piers




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About