djihed has asked for the wisdom of the Perl Monks concerning the following question:

I have a routine foo() that I'd like to call when a module Mod gets loaded, either with use or require. foo() may also accept an argument from the use function:
package Mod; use... { foo(); } sub import { my ($pkg, %options) = @_; __PACKAGE__->foo(arg => $options{-arg}); }
-arg specifies the name of a resource to load at import time with some default values. I'd like foo to die if the resources cannot be loaded from the default values. The conflict arises because the user has the option to use "use" or "require". Suppose that foo() will die on default values:
require Mod; # dies, good. use Mod; # dies, good. use Mod -arg => 'custom'; # dies, BAD.
How to resolve this?

Replies are listed 'Best First'.
Re: use, require, import and use arguments
by jethro (Monsignor) on Feb 25, 2011 at 17:32 UTC

    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.

      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