简体   繁体   中英

Extending perl module from within the calling script

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!

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.

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(); 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM