Passing arguments to a perl package while using it

青春壹個敷衍的年華 提交于 2020-12-05 08:37:29

问题


How to pass some arguments while using a package, for example:

use Test::More tests => 21;   

I wasn't able to find any valuable documentation about this featue. Are there any pros and cons of passing such arguments?


回答1:


use My::Module LIST does two things: 1) It requires My::Module; and 2) Invokes My::Module->import(LIST).

Therefore, you can write your module's import routine to treat the list of arguments passed any which way you want. This becomes even easier if you are indeed writing an object oriented module that does not export anything to the caller's namespace.

Here's a rather pointless example:

package Ex;

use strict;
use warnings;

{
    my $hello = 'Hello';
    sub import {
        my $self = shift;
        my $lang = shift || 'English';
        if ($lang eq 'Turkish') {
            $hello = 'Merhaba';
        }
        else {
            $hello = 'Hello';
        }
        return;
    }

    sub say_hello {
        my $self = shift;
        my $name = shift;

        print "$hello $name!\n";
        return;
    }
}

__PACKAGE__;
__END__

And a script to use it:

#!/usr/bin/env perl

use strict;
use warnings;

use Ex 'Turkish';
Ex->say_hello('Perl');

Ex->import;
Ex->say_hello('Perl');

Output:

$ ./imp.pl
Merhaba Perl!
Hello Perl!



回答2:


Some may say it is more readable in some scenarios, but in essence it is same as

use Test::More qw(tests 21);

(test is auto-quoted by fat comma =>, and number doesn't need quote).




回答3:


The major disadvantage is that you can't use the default import subroutine from Exporter, which expects only a list of symbols (or tags denoting collections of symbols) to import into the calling package

Test::More inherits a custom import routine from the superclass Test::Builder::Module, which uses the arguments supplied in the use statement to configure the test plan. It also in turn uses Exporter to handle options specified like import => [qw/ symbols to import /]

Pretty much anything can be done by a custom import subroutine if you have a specific requirement, but it is probably unwise to stray too far from standard object-oriented semantics



来源:https://stackoverflow.com/questions/30666896/passing-arguments-to-a-perl-package-while-using-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!