This is really more of a question of how to pass a variable to a sub.  First
off, check out perldoc perlsub.  To avoid problems like this, 'use strict'
whenever possible at the top of your scripts.

Anyway, here's how to fix this:

Passing a variable to a sub:  All variables passed to subs are put into the
@_ array and then passed.  Thus, when you do a printStatement($var), the
contents of $var are passed to the first element of the @_ array.  In the
sub in your module, there is no such thing as the variable $var.  If you had
used 'use strict', you would have generated an error.  So what you need to
do is change your module as follows:

########################

#!/usr/bin/perl
use strict;
package HelloWorld;
require Exporter;

our @ISA       = qw(Exporter);
our @EXPORT    = qw(printStatement);

our $VERSION   = 1.00;

sub printStatement { print $_[0] }

1;

########################

One small problem that this prestents is that you can not pass more than one
array to a subroutine.  If you do, then they will both be stuck together in
the @_ array.  That is where you start getting into references.


Some suggested reading:

perldoc perlsub
perldoc perllol
perldoc -f my
perldoc -f our

There is an article out there on the Web called "Coping with Scoping".  I
really recommend everyone read it.

-----Original Message-----
From: jeff [mailto:[EMAIL PROTECTED]]
Sent: Tuesday, October 15, 2002 4:30 PM
To: [EMAIL PROTECTED]
Subject: passing a variable to a module



Quick question. I want to pass a variable to a non-oo module that I
created. But I how do I get the module to contain the value of the
variable that was created in the 'main' namespace. I think there is
something easy that I am not understanding. Example code below.

PROGRAM BEGIN
#!/usr/bin/perl
use HelloWorld;

$var = 'hello world';

printStatement;
exit;
PROGRAM END

MODULE BEGIN
#!/usr/bin/perl

package HelloWorld;
require Exporter;

our @ISA       = qw(Exporter);
our @EXPORT    = qw(printStatement);

our $VERSION   = 1.00;

sub printStatement { print $var; }

1;
MODULE END

THINGS I'VE TRIED BEGIN
I've tried passing in $var to printStatement,
printStatement($var)
in the program

I've tried using the 'main' namespace in the module
print $main::var;

I've tried passing a reference the $var in the module
printStatement (\$var);

THINGS I'VE TRIED END

Executive summary: how do I define a variable in my program and have a
module use that variable definition (in a non-oo module).

Jeff





-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to