I've tried passing in $var to printStatement
that should work, as long as your module subroutine retrieves the variable properly. When you call sub($var), it's the value of $var, not the variable itself, that gets handed over, so you can't retrieve it by asking for $var in the sub, as use strict will point out.
Instead, the parameters passed to a subroutine are available within it as a flattened list in @_, which by great good fortune is the default subject of the shift function. Hence the very common idiom:
printStatement('foo'); sub printStatement { # @_ is ('foo') my $var = shift; # $var is now what was $_[0], the first item in @_, ie 'foo' print $var; } # or just sub printStatement { print shift }
I've tried using the 'main' namespace in the module
not such a good plan. the idea is not to mingle namespaces, so that you don't have to wander through your modules trying to work out who changed what. There are circumstances where it makes sense to do it the other way around, but they're few and special (eg mod_perl startup scripts):
$HelloWorld::var = 'foo'; printStatement();
I've tried passing a reference the $var in the module
nothing wrong with that either, and often the best approach (eg if you think the interface to your module may change later to make this function accept parameters that might include lists or hashes). You just have to make the printStatement sub retrieve the variable from @_ and dereference it before printing:
my $important_message = 'foo'; printStatement(\$important_message); sub printStatement { my $var = shift; print $$var; }
perlsub has the details, and how to rtfm has how to get there, thanks to masem.
updated for clarity
In reply to Re: variable passed to module
by thpfft
in thread variable passed to module
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |