Bloodnok has asked for the wisdom of the Perl Monks concerning the following question:

A happy new year to all you venerable monks,

I hope this node isn't a harbinger of things to come this year ... just when I thought I was beginning to understand something, along comes the fickle finger of fate to point out the following (AFAICT) anomaly: running this one-liner doesn't produce the expected fatal not an object error....

pointo1d@unforgiven:~/workspace/SVC-ArgsParser$ perl -Mstrict -we 'sub + can_it { $_[0]->can(qw/can/) } my $f = qw/fred/; $f->can(qw/isa/); c +an_it(qw/fred/)' pointo1d@unforgiven:~/workspace/SVC-ArgsParser$
Deparse shows, AFAICT, that there's nothing untoward going on from a parsing POV...
perl -MO=Deparse -we 'use strict ; sub can_it { $_[0]->can(qw/can/) } +my $f = qw/fred/; $f->can(qw/isa/); can_it(qw/fred/)' BEGIN { $^W = 1; } sub can_it { use strict 'refs'; $_[0]->can('can'); } use strict 'refs'; my $f = 'fred'; $f->can('isa'); can_it 'fred'; -e syntax OK
Question is, am I, once again, missing something obvious ? I was expecting a fatal error, at the very least, from the $f->can(qw/isa/) statement - but self-evidently didn't get one ... from either of the potential sources !!

FWIW, I'm running 5.8.8 on Ubuntu.

A user level that continues to overstate my experience :-))

Replies are listed 'Best First'.
Re: Arrgh, can() appears to work for non-object !!
by ysth (Canon) on Jan 07, 2009 at 11:23 UTC
    can and isa work on classes as well as objects. You are testing to see if the class fred has a can method, which it does since every class inherits from UNIVERSAL.

    Scalar::Util::blessed can be your friend:

    sub can_it { blessed($_[0]) && $_[0]->can('can') }
      TFT ysth,

      Yes, I know both can and isa work on both classes and objects, the thing is how can fred be a class ? Shouldn't I have expected a method can not found for class fred, did you forget to load fred ? type of error ?

      A user level that continues to overstate my experience :-))
        No, since nothing about a class is required. It need have no methods, @ISA, or anything else, so there's nothing missing to provoke a "forget to load" kind of error. Even the package statement isn't required, since you can declare anything using a fully qualified name if you want.