Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PM Using Variables From Main Script 1

Status
Not open for further replies.

embonha

Programmer
Jan 13, 2003
3
US
Ok, I have a main script and a module I wrote, I will simplify to see if you can help.

<---------- MAIN SCRIPT ---------->


!/usr/bin/perl
use strict;
use myPM;

my $var = 'Hello World';

say_hi();

<---------- myPM SCRIPT ---------->

package myPM;

use strict;
require Exporter;
our @ISA = qw (Exporter);
our @EXPORT = qw (say_hi);

sub say_hi {
print $main::var . &quot;\n&quot;;
}

1;


I would hope this would print 'Hello World' but it prints nothing. Everything calls right, I have confirmed that the actual fucntion is being called etc. However, I just seem to have the syntax of the main::var thing wrong. Any help would be greatly appreciated.
 
I think the more 'standard' way (and extensible way) of doing this is to pass the variable to the subroutine.
Code:
# in package myPM
sub say_hi {
    my $var = shift;
    print &quot;var: $var\n&quot;;
}

######

# in main
my $var = 'Hello World';
say_hi($var);
The other way would be to make $var a package variable in the myPM package and set it in the main program.
Code:
# myPM
our $var;
sub say_hi {
    print &quot;var: $var\n&quot;;
}
########

# main
$myPM::var = 'Hello World';

say_hi();
Which you use depends on the actual implementation.
jaa
 
I had originally done exactly what you said in your first example. However, the variables being passed ended up being insane. I ended up with TOO MANY variables to really manage and still be able to understand the code. The PM I am trying to write is for an application and thus the need for portability or reuse is not really needed.

I have also considered putting all the variables in a hash and then pass them. I suppose I could do this, but I really thought there was a way to pull a value for a variable directly using the <caller>::<variable> syntax which is what I was hoping for.

Any other ideas? And, thanks for the reponse!
 
Well, if you want to do it that way then you need to declare $var as an [tt]our[/tt] variable rather than a [tt]my[/tt] variable in the main package. A variable declared with [tt]my[/tt] doesn't exists in the package symbol table and, therefore, cannot be accessed using the double-colon package variable notation.
So your declaration in the main program should be
Code:
our $var = 'Hello World';
jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top