Module questions (perhaps a module creation mini-tutorial)

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-bullshit-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
0
rabbit
3/25/2005 6:45:28 PM
perl.beginners 29388 articles. 4 followers. Follow

1 Replies
636 Views

Similar Articles

[PageSpeed] 14

On Mar 25, Peter Rabbitson said:

> package CalcTest;
>
> use warnings;
> use strict;
>
> my @collect;

This is suspect.  You shouldn't be using this array.  You should be 
storing data in your object.

> 1;

It's probably safer to put this at the very end of your module, just in 
case you have other code (non-subroutine code) that could possibly return 
false.

> sub new {
>
>    my $class = shift;
>
>    my $self = {};
>
>    @collect = (0,0,0);
>
>    bless $self, $class;
>
>    return $self;
> }

How about:

   sub new {
     my $class = shift;
     my $self = [ 0, 0, 0 ];
     bless $self, $class;
     return $self;
   }

Now instead of using an outside array, each object will have its OWN three 
numbers.

> sub add {
>
>    print (shift @_);

The first argument to ANY method is the class or object that invoked the 
method.  $_[0] is the object in this case.

>    if ( (scalar @_) != 3) {
>        return undef;
>    }
>
>    my ($var0, $var1, $var2) = @_;
>
>    $collect[0] += $var0;
>    $collect[1] += $var1;
>    $collect[2] += $var2;
>
>    return 1;
> }

How about:

   sub add {
     my $self = shift;
     return unless @_ == 3;
     $self->[0] += shift;
     $self->[1] += shift;
     $self->[2] += shift;
     return 1;
   }

That uses the object $self, which is an array reference, and adds one 
argument to each element of @$self in turn.

> sub result {
>
>    return @collect;
> }

Here, it'd be:

   sub result {
     my $self = shift;
     return @$self;
   }

> #### 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 interface to the module hasn't changed at all, so the code above 
should still work.

> 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).

You were misunderstanding the output of printing the object.  It printed 
something like

   CalcTest=HASH(0x....)

That's what an object looks like when you print it.  Class=TYPE(ADDR).

You typically STORE information in the object.  Your code was ignoring it 
entirely.  There was no need for your code to be "object-oriented" at all.

> 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?

Blessing a reference tells Perl that the reference is now an object of a 
specific class, and can invoke methods of that class with the $obj->method 
syntax.

> 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.

You were using @collect poorly.  With your code, you couldn't have TWO 
instances of a CalcTest.  Any work the first instance did would be erased 
when the second instance is created, and after that, both instances would 
always return the same results.

> 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?

If there is no explicit return value for a function, it returns the LAST 
thing it evaluated.

As far as documentation goes, please read

   perldoc perlboot

-- 
Jeff "japhy" Pinyan         %  How can we ever be the sold short or
RPI Acacia Brother #734     %  the cheated, we who for every service
http://japhy.perlmonk.org/  %  have long ago been overpaid?
http://www.perlmonks.org/   %    -- Meister Eckhart
0
japhy
3/25/2005 7:23:22 PM
Reply:

Similar Artilces:

To module or not to module that is the question
Howdy List,=20 Bit of a quandry here. I have a script that does everything it's supposed to. It's basically like this: ---------------------- Configuration variables here: Program flow here with a single print statement after=20 it figures out what it's doing based on the configuration and user = input. ------------------ Now I need to use this same script lots of times so I already have = differen configurations saved as different modules then in the script = all I have to do is: ------------ In One.cgi: use Special::One; # this brings in all the configuar...

modules, modules
This site appears to be the most comprehensive list of free custom modules: www.dnnfaq.com Any other sites? I do like how Rainbow gives you a bucket of them - saves a lot of time over having to snoop around and find some of the DNN ones. Is there also a way to list modules as "certified"? Also - is there a decent repository of skins? I have recently installed version 2.0. Sure wish there were more modules ready for it! That would make it much easier to evaluate the program and give recommendations to my boss. The reason there aren't more 2.0 modules yet is becasue it h...

Module in Module
Hi, Is there a way to place a module inside another module (e.g. A feedback module inside a Text/HTML module) ? Cheers Tassos There is a way to inject controls into a module dynamically based on some criteria like a querystring parameter - is that what you are wanting to do?Dylan Barberread my stupid blog http://codemypantsoff.com There's a commercial module "wrapper" on Snowcovered that is designed to hold other modules.  So it is possible.I don't know if you could put a module holding a module inside a module containing a module, but I wouldn't try.  The entire space-time...

To Data Module or not Data Module, that is the question
Can anyone offer best practice advice please. Porting my access application to Delphi I have used a data module. It now has one Tdataconnection and lots and lots of TDAOQueries and TDAOTables on it. Its now getting hard to see the wood for the trees. My question is twofold. 1) is is best to use a data module or just use the TDOQueries I need on each form? 2) is it best to use loads of TDAQueries, each with hard coded SQL or use just one or two with the sql string dynamically loaded just before I execute it. With Qn 2 it is starting to look bettert to dynamically load the sql from a f...

Module Creation Question
I’m confused. In order to create a new module in the newest version of DNN 2.0 do you have to create a PA. I use to be able to go create a folder under DeskTopModules and the module would could be add into the program through the module definition page and then show up in the module drop down list. This does not seem to work anymore. Do you have to create a PA now to get a new module into DNN? Kai Wen Seems like every module I create does not show when I try to display them on the content page. I get no errors. I don't understand. Do I have to make a PA to get a new module into D...

Module Creation Tutorial
Hello, I am new to DNN and am trying to learn how to make my own modules for it. I have been searching online for hours now and cna't find any tutorials for DNN 3.x, just 2.x. I may have just been looking in the wrong places, or the ones I did find made no sense to me, not sure which. I was wondering if anyone here could point me to a good resource for learning how to make DNN 3x modules. The more resources the better, but someting would be a good start. Sorry if this has been asked a million times before. "Even the wisest of the wise may err."  Baatezu wrote:Hello,I am ne...

module name for a tutorial or example or sample module
I have a XS module I wrote as a sample=2C example or tutorial on how to do = increase the performance of perl hashes on an XS level. It doesn't do anyth= ing useful on its own other provide 2 XSUBs which are supposed to be benchm= arked against each other to show the traditional vs my "new" way of doing t= hings. It exports nothing C/.so/.a/.lib/.dll or Perl wise. It's test file j= ust does the benchmark. It doesn't link with anything except a stock perl a= nd a stock c std lib. It only real purpose is to be copied into other XS mo= dules and be studied from. Wha...

Load module into module...
Is it possible to load a module into another module? I'm thinking in particular of the Internal Links Module available @ www.cortinc.com I use this module a lot and with a few enhancements it has served me well, however it has one flaw...each link only allows html data...because it is just a holder that loads the html from the db. It would be a great enhancement to be able to add other modules to these links i.e. announcements, news, pictures etc but they would in effect have to be loaded into another module. Any thoughts would be appreciated on how I should approach this or whether it...

A Module inside a Module ??
Hi DNN Community, I've developed a DNN module (let's call it module X) which is included in my DNN website as a private assembly. However, I'l like to add a scrolling marque usercontrol to my module X. As a start, I purchased a scrolling marquee module from snowcovered which works great as a stand alone module. However, I'd like to modify this module so it fits into my module X. Can anyone explain to me how to do this, and if there is any source code available where I could see how this is done. Thanks in advance, Brad How about putting a placeholder control in your module X then...

Modules and information about modules.
As we live in a word with different localization issues I think it would bee nice to tell byers and user if the module can handle different cultures and of cource if the module are localized or not. Sometimes it doesent matter that the module have static localization you can use it anyway. But if the date format or any other localized value are used inside the module I think it is essential to tell too. As an example I can tell that Portal Store just works if you use the US date format. So if you like to use it in non us english you have to go through the code and correct it. As I know th...

How to load modules into modules
Title says it all. I want to load (custom) modules within a custom module. But I havent the slightest idea how to do that. Any suggestions? thx Like this: Dim _MyControl as _MyControl _MyControl = CType(Me.LoadControl("MyControl .ascx"), MyControl) ParentControl.Controls.Add(_MyControl) Leigh PointerUser Group Champion » Evangelising DotNetNuke Everywhere « The method LoadControl works, if your loaded custom module doesn't need do raise PostbackEvents :-( If you need that... Than this way is impossible for you. I will post how to do it right in...

Module to Module Communication
Does anyone have an example of how to implement module-module communication/event handling using DNN2? I have tried to look through the portal code and try to figure it out for myself but not much luck :) Tom Gruszowskiemail: [MyUserName]@hotmail.com To answer my own question I found the following link. Any other resources and solid examples that anyone else would like to share? http://xpdit.com/DeskTopDefault.aspx?tabid=1&BookID=13&ChapterID=69&PageID=242Tom Gruszowskiemail: [MyUserName]@hotmail.com I seem to remember an example on kodhedz.netMatt FraserDotNetNuke Co...

sub modules, loading custom modules into a parent module
GreetingsI am creating a support system module which will require the ability to add sub modules. For example, there is an admininstrators section in which suport requests are administered, anwsered, solved etc.There is to be another function in the admin section of the support module in which admins can upload a new support form template module, ie, say an admin wants to set up a form for users to lodge a request for new hardware, the form will display all required fields, graphics, validation etc for that request. Another support form template might be to have a new user set up on the acti...

Modules within Modules
I purchaced the Internal Link Navigation from Snowcovered a while back and have modified it so I can insert user controls in the child-level pages. However, if I try to insert a IBS module, it returns an error because the IBS modules use desktopcontols.vb to pull properties for the module from the database and I haven't set that up properly. When I look at the code in tablayout.aspx.vb I have a hard time sorting through it. Any ideas? Do you want to post your mods to Internal Link Navigation - I have done a fair bit of work with that so may be able to help Or email the code to me Dav...

Web resources about - Module questions (perhaps a module creation mini-tutorial) - perl.beginners

Resources last updated: 11/27/2015 3:32:34 AM