Search code examples
perlperl-module

What happens in these Perl use lines?


I don't understand what happens here :

use PAR { file => 'foo.par', fallback => 1 };

I think that's an anonymous hash. How is a module using it from the use line? Can you shed some light?

EDIT: I'm not interested in the PAR module. I'm just interested in how that works behind the curtain. How can I configure my modules like that?


Solution

  • More basically, this is what the funny hashref syntax does (using perldoc -f use as a reference):

    Say we have this basic module (put it in Foo.pm in your current directory):

    package Foo;
    
    use Data::Dumper;
    sub import
    {
        print "import was passed these arguments: ". Dumper(\@_);
    }
    
    1;
    

    when we call perl -I. -wle'use Foo { a => 1, b => 2}', the code Foo->import({a=>1, b=>2}) is executed. So this is what we get as output:

    import was passed these arguments: $VAR1 = [
              'Foo',
              {
                'a' => 1,
                'b' => 2
              }
            ];
    

    Basically, this syntax lets us do magic with the Exporter, but in truth you can make import() do anything you like (just be sure to document heavily so as to not cause confusion!)