Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i export a function named 'import' from a module in Perl?

Tags:

perl

I've written a special import function that will be used in a few places and I'd like to be able to just go "use ImportRenamer;" in those modules and have them use the import gained from ImportRenamer henceforth. How would i go about that?

Edit: In other words: How do i import 'import' without running it?

like image 247
Mithaldu Avatar asked Dec 23 '22 00:12

Mithaldu


1 Answers

UPDATE

Now that OP clarified his needs, this should indeed be done in a way similar to what Exported does, to be precise, by injecting the sub reference into a caller's namespace via a glob assignment. Example:

###############################################

package ImportRenamer; 
use strict;
sub import_me {
   print "I am a cool importer\n";
}

sub import { 
  my ($callpkg)=caller(0);
  print "Setting ${callpkg}::import to ImportRenamer::import_me\n"; 
  no strict "refs";
  *{$callpkg."::import"} = \&ImportRenamer::import_me; # Work happens here!!!
  use strict "refs";
}
1;

###############################################

package My; 
use strict;
use ImportRenamer; 
1;

###############################################

package My2; 
use strict;
use ImportRenamer; 
1;

###############################################

And the test:

> perl -e '{  package main; use My; use My2; 1;}'
Setting My::import to ImportRenamer::import_me
I am a cool importer
Setting My2::import to ImportRenamer::import_me
I am a cool importer

ORIGINAL ANSWER

You don't need to do anything special beyond calling the import method "import". use already calls import(), see perldoc use:

use Module LIST 

Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package.

It is exactly equivalent to:

 BEGIN { require Module; Module->import( LIST ); }
like image 140
DVK Avatar answered Dec 24 '22 14:12

DVK