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!

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.

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(); 
2
  • Thanks everbody for your help! :)
    – user1598019
    Jan 1 '13 at 20:41
  • You're welcome. Please accept one of the answers as the best by clicking the grayed out check mark. Jan 1 '13 at 20:44
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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy