| 1 | package UNIVERSAL::can; | ||
| 2 | # ABSTRACT: work around buggy code calling UNIVERSAL::can() as a function | ||
| 3 | $UNIVERSAL::can::VERSION = '1.20140328'; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use 5.008; | ||
| 7 | |||
| 8 | use vars qw( $recursing $always_warn ); | ||
| 9 | |||
| 10 | use Scalar::Util 'blessed'; | ||
| 11 | use warnings::register; | ||
| 12 | |||
| 13 | my $orig; | ||
| 14 | |||
| 15 | BEGIN | ||
| 16 | { | ||
| 17 | $orig = \&UNIVERSAL::can; | ||
| 18 | |||
| 19 | no warnings 'redefine'; | ||
| 20 | *UNIVERSAL::can = \&can; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub import | ||
| 24 | { | ||
| 25 | my $class = shift; | ||
| 26 | for my $import (@_) | ||
| 27 | { | ||
| 28 | $always_warn = 1 if $import eq '-always_warn'; | ||
| 29 | no strict 'refs'; | ||
| 30 | *{ caller() . '::can' } = \&can if $import eq 'can'; | ||
| 31 | } | ||
| 32 | } | ||
| 33 | |||
| 34 | sub can | ||
| 35 | { | ||
| 36 | my $caller = caller(); | ||
| 37 | local $@; | ||
| 38 | |||
| 39 | # don't get into a loop here | ||
| 40 | goto &$orig if $recursing | ||
| 41 | || ( defined $caller | ||
| 42 | && defined $_[0] | ||
| 43 | && eval { local $recursing = 1; | ||
| 44 | warnings->unimport( 'UNIVERSAL::isa' ) | ||
| 45 | if $INC{'UNIVERSAL::isa'}; | ||
| 46 | $caller->isa(blessed $_[0] || $_[0]) } ); | ||
| 47 | |||
| 48 | # call an overridden can() if it exists | ||
| 49 | my $can = eval { $_[0]->$orig('can') || 0 }; | ||
| 50 | |||
| 51 | # but only if it's a real class | ||
| 52 | goto &$orig unless $can; | ||
| 53 | |||
| 54 | # but not if it inherited this one | ||
| 55 | goto &$orig if $can == \&UNIVERSAL::can; | ||
| 56 | |||
| 57 | # redirect to an overridden can, making sure not to recurse and warning | ||
| 58 | local $recursing = 1; | ||
| 59 | my $invocant = shift; | ||
| 60 | |||
| 61 | _report_warning(); | ||
| 62 | return $invocant->can(@_); | ||
| 63 | } | ||
| 64 | |||
| 65 | sub _report_warning | ||
| 66 | { | ||
| 67 | if ( $always_warn || warnings::enabled() ) | ||
| 68 | { | ||
| 69 | my $calling_sub = ( caller(2) )[3] || ''; | ||
| 70 | warnings::warn("Called UNIVERSAL::can() as a function, not a method") | ||
| 71 | if $calling_sub !~ /::can$/; | ||
| 72 | } | ||
| 73 | |||
| 74 | return; | ||
| 75 | } | ||
| 76 | |||
| 77 | 1; | ||
| 78 | __END__ |