开发者

How do I read args passed to the constructor and args passed by `use Module` in Perl?

Currently I am making a new module and I was wondering how could I implement in my module 2 things.

We often see the use like:

use My::Module qw(something);

for example:

use CGI::Carp qw(fatalsToBrowser);
  1. So the first question is, how do i retrieve this, i mean wether the user has specified anything and what he specified ?

  2. Second question is, How do i pass开发者_开发知识库 and read the args directly on the constructor like this:

    my $my_module = My::Module->new(arg1,arg2,arg3);

AS requested on the comment the simple module test code:

package My::Module;

# $Id$

use strict;
use Carp;

sub new {
        my $class = shift;
        my $self  = {};

        $self->{ARG1}         = undef;
        $self->{ARG2}         = undef;
        $self->{ARG3}         = undef;
        $self->{ARG4}         = undef;

        bless($self,$class);
        return $self;
}

sub arg1 {
        my $self = shift;
        if (@_) { $self->{ARG1} = shift }
        return $self->{ARG1};
}

sub arg2 {
        my $self = shift;
        if (@_) { $self->{ARG2} = shift }
        return $self->{ARG2};
}

sub arg3 {
        my $self = shift;
        if (@_) { $self->{ARG3} = shift }
        return $self->{ARG3};
}

sub arg4 {
        my $self = shift;
        if (@_) { $self->{ARG4} = shift }
        return $self->{ARG4};
}

sub dump {
        my $self = shift;

        require Data::Dumper;
        my $d = Data::Dumper->new([$self], [ref $self]);
        $d->Deepcopy(1);
        return $d->Dump();
}

1;  # so the require or use succeeds


perldoc -f use explains that the use keyword is simply loading a module during compile-time, and then calling ->import on it. The arguments a caller gave to the use statement will be passed to the import method call.

As for your second question: constructors are just methods. Getting their arguments works like it does for any other method or function, using the @_ variable.


import subroutine gets the arguments passed in a use. The following code samples should help you.

File: My/Module.pm

package My::Module;

use warnings;
use strict;

use Data::Dumper;

sub import {
    my ( $package, @args ) = @_;

    print Dumper \@args;
}

1;

File: module.pl

#!/usr/bin/env perl

use warnings;
use strict;

use My::Module qw(something);

If you are programming an object oriented module, you may try Moose which will save you lots of time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜