1

Is it possible to extend a perl module from withing the calling script?

Something like that:

#!/usr/bin/perl 

use strict; 
use Some::Module; 

Some::Module::func = sub {
  my $self = shift; 
  # ...
}


my $obj = new Some::Module; 

$obj->func(); 

Thanks a lot!

3 Answers3

5

You seem to want to add subs to a package. You almost have it:

|
v
*Some::Package::func = sub {
   ...
};
 ^
 |

But if you know both the name and the sub body, why are you doing it at run-time? Maybe you actually want

sub Some::Package::func {
   ...
}

or

{
   package Some::Package;
   sub func {
      ...
   }
}

or since recently,

package Some::Package {
   sub func {
      ...
   }
}

Note that you almost certainly have a poor design if you are doing this.

ikegami
  • 367,544
  • 15
  • 269
  • 518
4

You can do what you're talking about with typeglobs, but the easier way is to do this:

use Some::Module; 

package Some::Module;

sub func {
  my $self = shift; 
  # ...
}

package main;

my $obj = new Some::Module; 

$obj->func(); 
Andy Lester
  • 91,102
  • 13
  • 100
  • 152
2

Yes. You can declare the package you want to add subs to, and just add them.

package Some::Module {
  sub func {
  my $self = shift;
  # ...  
  }
}

Or see perldoc package for more info.

If you want to overwrite a sub instead, you need to use typeglobs.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 1
    See http://stackoverflow.com/questions/11773234/is-it-possible-to-redefine-subroutines-to-be-localized-for-a-part-of-the-code/11773664#11773664 and http://stackoverflow.com/questions/449690/how-can-i-monkey-patch-an-instance-method-in-perl for the typeglob thing. – simbabque Dec 26 '12 at 23:14