in reply to use, require, import and use arguments

I tried the following:

package Mod; sub foo { print "Output: @_\n"; } sub import { my ($pkg, %options) = @_; __PACKAGE__->foo(arg => $options{-arg}); } 1;

Result:

> perl -e 'use Mod -arg => "custom";' Output: Mod arg custom

No dying at all.

Replies are listed 'Best First'.
Re^2: use, require, import and use arguments
by djihed (Novice) on Feb 26, 2011 at 12:59 UTC
    I was not clear why foo died. Consider:
    package Mod; sub foo { my ($pkg, %options) = @_; my $dir = $options{arg} || "/default"; die "$dir not found" unless -d $dir; print "$dir found"; } # this is to make foo run when module is require'd { foo(); } sub import { my ($pkg, %options) = @_; __PACKAGE__->foo(arg => $options{-arg}); }
    This:
    perl -e "use Mod -arg => '$HOME';"
    Dies - I don't want this. I want foo to run with both "require" and "foo" and properly run without dying when the use" pragma gives it an argument.
      Because '$HOME' is not a directory that exists? In perl , there is no variable $HOME, and single quotes do not inerpolate

      I have no idea if your shell would interpolate $HOME into that commandline

        It does - it's just an example. If it doesn't suppose that $HOME is replaced by some real existing directory. The reason it dies is because foo is called first in the block above import.