in reply to Re: Re: Re: Perl module symbol import versus direct invocation
in thread Perl module symbol import versus direct invocation

I agree it's very annoying that on the callee side, i.e. in the sub, it's virtually impossible to distinguish between being called as a function or as a method. Looks at the mess CGI.pm made of it — look into the subs "self_or_default" and "self_or_CGI".

A reason to have calls as class methods instead of as functions, is the simple fact that now, inheritance works. It doesn't when you call a sub as a function.

Two rather well known class methods are import, automatically invoked by use — and often inherited :-) from Exporter, and new, a name people often choose for a sub that serves to create a new instance of a class.

  • Comment on Re: Re: Re: Re: Perl module symbol import versus direct invocation

Replies are listed 'Best First'.
Re^5: Perl module symbol import versus direct invocation
by adrianh (Chancellor) on Feb 26, 2003 at 14:00 UTC
    I agree it's very annoying that on the callee side, i.e. in the sub, it's virtually impossible to distinguish between being called as a function or as a method.
    { package Foo; use Devel::Caller qw(called_as_method); sub new { bless {}, shift } sub foo { my $arg = shift; if (called_as_method(0)) { ref($arg) ? "object method" : "class method"; } else { "subroutine"; } } } use Test::More tests => 3; my $foo = Foo->new; is( Foo->foo, "class method" ); is( $foo->foo, "object method" ); is( Foo::foo($foo), "subroutine" );

    (although wanting to do this in real code is nearly always a sign that you need to rethink your design :-)