Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to a perl package while using it

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?

like image 912
Robert Avatar asked Jun 05 '15 12:06

Robert


People also ask

How do you pass an argument in Perl?

If you want to use the two arguments as input files, you can just pass them in and then use <> to read their contents. Alternatively, @ARGV is a special variable that contains all the command line arguments. $ARGV[0] is the first (ie. "string1" in your case) and $ARGV[1] is the second argument.

What is $# ARGV in Perl?

The variable $#ARGV is the subscript of the last element of the @ARGV array, and because the array is zero-based, the number of arguments given on the command line is $#ARGV + 1.

How do you pass a parameter to a subroutine?

To pass parameters to a subroutine, the calling program pushes them on the stack in the reverse order so that the last parameter to pass is the first one pushed, and the first parameter to pass is the last one pushed. This way the first parameter is on top of the stack and the last one is at the bottom of the stack.


1 Answers

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!
like image 54
Sinan Ünür Avatar answered Oct 30 '22 14:10

Sinan Ünür