views:

55

answers:

2

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
+6  A: 

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.

rafl
+4  A: 

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.

Alan Haggai Alavi
awesome, really appreciated. I will take a look at Moose.
Prix