Module questions (perhaps a module creation mini-tutorial)

From: Peter Rabbitson (rabbit_at_rabbit.us)
Date: 03/25/05


Date: Fri, 25 Mar 2005 13:45:28 -0500
To: beginners@perl.org

Hello list,

I am trying to make my own modules for some tasks, and I am trying to grasp
the basics before I go any further. Here is a dumb test module that I wrote
just to see how things are done - it takes an array of 3 values and adds
them together, returning the values on request.

### 3-element-array-calc test module (CalcTest.pm)

package CalcTest;

use warnings;
use strict;

my @collect;

1;

sub new {

    my $class = shift;

    my $self = {};

    @collect = (0,0,0);

    bless $self, $class;

    return $self;
}

sub add {

    print (shift @_);

    if ( (scalar @_) != 3) {
        return undef;
    }

    my ($var0, $var1, $var2) = @_;

    $collect[0] += $var0;
    $collect[1] += $var1;
    $collect[2] += $var2;

    return 1;
}

sub result {

    return @collect;
}

#### main perl program (test.pl)

use warnings;
use strict;

use CalcTest;

my $calc = CalcTest->new();

print "error\n\n" unless $calc->add (3, 4, 5);

print "error\n\n" unless $calc->add (1, 2, 3);

print join (' * ',$calc->result);
print "\n\n";

exit 0;

The thing works, however there are too many unclear issues.

1. Everytime I call one of the subroutines (methods I believe they are
called?) I get a hash in $_[0] with only one value - the string name of the
package I am calling. What defines the contents of this hash? Is it always
just this single value pair or there might be additional values? If yes -
what kind? (A reference towards *clear* documentation would be best).

2. The idea of blessing... I understand the idea, I don't understand the
reason. Why does bless need an empty hash intialized for it to bless it?
Isn't blessing completely symbolic? Or I actually might put something in
\%self ? If I do - what does this give me?

3. The usage of my in a package - here and there I see clues that 'my' does
behave differently when used in a module - is this true? Is it correct do
declare a package-wide @collect and have subroutines work on this
semi-global variable (global from the package point of view), so I can get
results that stack-up - the addition in the above example, or the
accumulation like in Text::CSV where you keep pushing data in, and then you
wrap a string... you probably see where I am going.

4. If I don't define an explicit return value for a sub - is it always undef
(like I would expect) or the package occasionally might decide to assign
something as a return value?

Btw, a disclaimer to cover my private body parts - I searched extensively
enough (imho) for a good tutorial on this subject and all the docs follow
same theoretical-bull***-endeavor model without actual low level
explanation. As a matter of fact I would never be able to write
the above code correctly without looking at an actual source of a CPAN
module (Text::CSV to be exact).

Thank you.

Peter