For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2005 > Package question









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Package question
Luinrandir

2005-07-25, 5:30 pm

I am just learning about making and using my own packages and moduals


I have a CGI that requires a package.
the package is a subroutine that is called on in the main program(CGI)
The subroutine works fine as a sub in the main program.
but when I put it in a package, it does not work.

I thought requiring it (in the first 10 lines of the main program) would be
enough
to use is.. do I have to call on it?


Main program
require package

do stuff here....
subroutine;

sub subroutine
{
do stuff here
}

OR---------

Main program
require package

do stuff here....
subroutine;

sub subroutine
{
call package???
}



John Doe

2005-07-25, 5:30 pm

Luinrandir am Montag, 25. Juli 2005 21.42:
> I am just learning about making and using my own packages and moduals
>
>
> I have a CGI that requires a package.


or: "uses"

> the package is
> a subroutine that is called on in the main program(CGI)
> The subroutine works fine as a sub


....defined...

> in the main program.
> but when I put it in a package, it does not work.


you have a namespace issue here, see below.

> I thought requiring it (in the first 10 lines of the main program) would be
> enough to use is..
> do I have to call on it?
>
>
> Main program
> require package
>
> do stuff here....
> subroutine;
>
> sub subroutine
> {
> do stuff here
> }
>
> OR---------
>
> Main program
> require package
>
> do stuff here....
> subroutine;
>
> sub subroutine
> {
> call package???
> }


In both code snippets, you redefine subroutine, which is not what you want.

you probably want:


a) the module:

package MyPackage;
use strict;
use warnings;

mysub {
...
}

1;

b) in your main script:

....
use MyPackage; # use your package
MyPackage::mysub(...); # call qualified sub from it
....


You could use the Exporter module to avoid the qualified call of the sub
defined in your module. I personally prefer to write more and call qualified
subs from my modules, because it is then obvious where they are defined and
it is easyer to search for them.

See the perl doc

perldoc perlmod

for information about modules and their usage.

joe
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com