[Mpls-pm] Dumb Question...Module Method - Dual Name

Ian Malpass ian at indecorous.com
Fri Oct 21 20:01:50 PDT 2005


On Thu, 20 Oct 2005, Gary Vollink wrote:

> If I have a Module that default exports:
> @EXPORT = qw/corvuDbSelect corvuDbRun corvuDbFetch/;
>
> But say, in a more sane OO land, I would want corvuDb dropped...
>
> -----
> require corvu::Db;
>
> $mydb = corvu::Db::new();
>
> $mydb->Select($sql);
> $mydb->Fetch($sql);
> -----
>
> This seems to work so far, but is it the right way...
>
> -----
> package corvu::Db;
> ...
> sub Select {
>   my $self = shift;
>
>   # DBD stuff...
>   # Specific Error Hanlding for me, etc
> }
>
> sub corvuDbSelect {
>   Select ( @_ );
> }
> -----

Except you'd need to do

sub corvuDbSelect {
   Select ( 'corvu::Db', @_ );
}

since Select() expects the class name as the first argument. Or an object. 
I don't think you can expect to do anything that requires $self to be an 
object in Select() if you want your function call version to work 
normally. Class methods would be OK if you pass in the class name as 
above.

You could also do stuff with AUTOLOAD, but it's a bit of a snare for the 
unwary.

  package Example;

  use strict;
  use warnings;
  use vars qw( $AUTOLOAD @EXPORT @ISA );

  require Exporter;
  @ISA = qw( Exporter );
  @EXPORT = qw( egFoo egBar );

  sub Foo {
    return "foo";
  }

  sub Bar {
    return "bar";
  }

  sub AUTOLOAD {
    $AUTOLOAD =~ /.*::(.+)/;
    my $method = $1;
    if ( $_[0] and ( ref $_[0] eq __PACKAGE__ or $_[0] eq __PACKAGE__ ) ) {
      die "Unknown method: $method";
    } elsif ( $method =~ /^eg(.+)/ and __PACKAGE__->can( $1 ) ) {
      return __PACKAGE__->$1( @_ );
    } else {
      die "Unknown subroutine: $method";
    }
  }

  sub DESTROY {
    # tidy up objects without calling AUTOLOAD
  }

  1;

Then you can do:

  % perl -MExample -e 'print egFoo(), "\n";'
  foo
  % perl -MExample -e 'print Example->Bar(), "\n";'
  bar
  % perl -MExample -e 'print Example::Baz(), "\n";'
  Unknown subroutine: Baz at Example.pm line 27.
  % perl -MExample -e 'print EG->Bat(), "\n";'
  Unknown method: Bat at EG.pm line 23.

Ian

-
---------------------------------------------------------------------------

The soul would have no rainbows if the eyes held no tears.

Ian Malpass
<ian at indecorous.com>


More information about the Mpls-pm mailing list