Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Common sub as method or function (or)

by tye (Sage)
on Aug 15, 2007 at 17:32 UTC ( [id://632806]=note: print w/replies, xml ) Need Help??


in reply to Common sub as method or function

You can compile the code for methods in a package other than the one used to look up methods (the one matching the class name), then you can put non-method utilities in that non-class package and use them directly w/o inheritance and without poluting your "method name" namespace.

package My::Class::SubClass; require My::Class::Base; @ISA= qw( My::Class::Base ); package My::Class::SubClass::_code; # Import common non-methods: My::Class::Base::_code->import( qw( _utilSub _timestamp ) ); # Export below methods to My::Class::SubClass: for( grep !/^_/, keys %{ __PACKAGE__ . "::" } ) { *{"My::Class::SubClass::".$_}= \&$_ if defined &$_; } use strict; sub new { my $us= shift @_; ... $us->someBaseMethod( @works ); _utilSub( _timestamp() ); ... }

Then you don't have to try to guess whether the first argument is an object or not. Perhaps more importantly, you don't have to worry about your users being confused when they access a utility function that has nothing to do with the object via a simple $obj->_timestamp(), since that would tell them that there is no _timestamp() method.

If you don't like the underscore, then you can list which methods to export rather than just exporting all subroutines that don't have a leading underscore.

Just because Perl 5 doesn't include a feature for distinguishing methods from non-methods, doesn't mean you have to throw all of those different items into the same namespace.

Note that this breaks SUPER:: and some naive OO doohickeys that try to rely on caller (which doesn't currently provide a proper class name for such uses).

If you want your users to be able to access the util sub as a method, then you can use this same technique (of compiling methods into a package other than the one having the name of the class) to provide both a method and non-method version without having to try to guess whether the first argument is an object:

package My::Class::Base; use vars qw( $VERSION ); $VERSION= 1.001_002; package My::Class::Base::_code; use vars qw( @EXPORT_OK ); BEGIN { require Exporter; *import= \&Exporter::import; @EXPORT_OK= qw( _utilSub _timestamp ); } use strict; sub _timestamp { # non-method code } # Method version: *My::Class::Base::_timestamp= sub { shift @_; return _timestamp(); }

- tye        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://632806]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2024-03-28 10:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found