0

I've written a perl module (say foo), with one primary subroutine (say f()), which I want to use in two ways:

  1. Import module foo , then call the sub f(...) from the script importing module foo.
  2. Just import module foo and get module foo to call the sub f(@ARGV) or some appropriate variation.

Can I make one module which has these two options,
or
Should I make a wrapper module, say foo_default.pm, which will use foo and then calls foo::f(@ARGV)?

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • Can you post some code that you tried for *some appropriate variation*? Because you can just export function as *sputnick* has shown you. and that will work for function call with arguments, just use `my $args = @_;` as first line in your function `f()`. –  Jan 09 '13 at 07:08

2 Answers2

2

The Classic Way

If you don't want to provide the fully qualified name of your function, you should export it :

package foo;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw/func1 func2/;

sub func1 { return "hi $_[0] !\n"; }
sub func2 { return "yo breakdown mama !\n"; }

So to use it :

# uncomment this if you need to add a "./lib" dir in @INC
# BEGIN{ push @INC, "./lib"; }

use foo;

my $res = func1("you");
print $res;
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

Example foo module:

package foo;

my $nodef = 0;

sub import {
  my ($package, $arg) = @_; 
  print "import called $arg\n";
  $nodef = 1 if (defined $arg && $arg eq 'nodef');
  f(@ARGV) if !$nodef;
}

sub f() {
  print "f() called: ", join(", ", @_), "\n";
}

1;

And the use case:

sub def {
  use foo;
}

sub nodef {
  use foo qw(nodef);
}

def();
nodef();
perreal
  • 94,503
  • 21
  • 155
  • 181