in reply to isa() on any scalar

Update: I agree with chromatic's point. When I thought of the solution below, I erroneously conflated the OP's problem with a different one (one resulting from using ref to detect whether something is an 'ARRAY').


Use UNIVERSAL::isa instead. I.e.

UNIVERSAL::isa( $value, "Node" )

the lowliest monk

Replies are listed 'Best First'.
Re^2: isa() on any scalar
by chromatic (Archbishop) on Jun 10, 2005 at 18:56 UTC

    No, don't do that.

    Assume that UNIVERSAL::new existed. Would you suggest always creating objects with UNIVERSAL::new( $class_name, %data ); too?

    Try instead:

    my $is_node = eval { $value->isa( 'Node' ) }; # handle not node case if $@ is true or if $is_node is false

    This has the advantage of allowing subclasses of Node to override isa() as they see fit, of allowing objects that perform the Node role (see Class::Roles, for example) to work appropriately, and of catching an error if $value is an invalid invocant. It also avoids calling a parent class method specifically on a potential instance of a derived class, which is a bad idea.

    Update: Expanded code slightly.

      No don't do this either. An exception should only be used to catch exceptional events. Since it seems that $value is just as likely not to be a 'Node' as it is to be one you should not use an exception to test it.
      -- gam3
      A picture is worth a thousand words, but takes 200K.

        As I mentioned, if $value is not a valid invocant, it is an exceptional case.

        I'm not aware of any other idiom that respects potentially-overridden isa() methods and handles potentially invalid invocants in one statement. If you know one, please share.

        Scalar::Util's blessed() is pretty good, but that technique disallows calling isa() as a class method. Sometimes that's good. Sometimes it's not.

Re^2: isa() on any scalar
by mrborisguy (Hermit) on Jun 10, 2005 at 18:07 UTC

    Thank you, this is exactly what I wanted. You get my ++ for answering the question. But after reading revdiablo's post below, I'm not sure if this is really what I want anymore. Maybe I'll have to spend some time rethinking my design.

        -Bryan

Re^2: isa() on any scalar
by nothingmuch (Priest) on Jun 11, 2005 at 12:34 UTC
    No no no!

    Every time a module does that a kitten using Test::MockObject dies.

    Please think of the kittens!

    -nuffin
    zz zZ Z Z #!perl
      Perhaps the kitten should choose a better way of mocking then. I suggest using the Parisian::Waiter::Scornful module.
        Perhaps not a better way of mocking, but a better way of introspecting.... I uploaded a new module that hacks around this stuff.
        -nuffin
        zz zZ Z Z #!perl