perl globalisation between packages

N

Newsgroups

Hi,

How can I globalise a hash variable with this context/example :

test.pl contains :
#!/usr/bin/perl
use myPackage;
my %hash;
$hash{"test"} = 10;
my $p = new myPackage;
$p->otherSub();
print $hash{"test"}; # will print 10; but I would like it to print 11

and myPackage.pm contains :
#!/usr/bin/perl
package myPackage;

sub otherSub {
$hash{"test"}++; # here, my hash isn't global
}
1;


And, I doesn't want to pass my hash into to sub like this :
$hash = $p->otherSub($hash{"test"}); with a "return $hash" into
otherSub.

I've tryed to use @EXPORT= qw($hash) without success.


Thanks for your advices...
 
N

Newsgroups

Le lundi 04 décembre 2006 à 14:08 -0500, Sherm Pendley a écrit :
Poor choice of variable name,
It was for the example :)
If you wanted to export it from myPackage, you shouldn't be declaring it here at
all.
In fact, I would like to share it throught test.pl, myPackage1.pm and
myPackage2.pm

If you *do* want to declare it as a package variable in the default package
main::, you'd use "our" to declare it here instead of "my":
our %hash;
Hum, I've tryed this.

I assume you have a new() method in myPackage, but didn't include it in
your message.
Yes, new() method just initialize some vars for the package.


Please read the posting guidelines that are posted here at
least twice a week; it's expected that you post a short and *complete*
example that illustrates the problem you're having.
It will be difficult if I post the complete code : 3 packages, about
1000 lines each
This is the reason why I just post an example

So, this is a more speaking example : I hope !
main.pl
#!/usr/bin/perl


use user;

my $user = new user();

my $hash = ();
$hash->{"t"} = 0;
$hash->{"QtyUsers"} = 0;
$hash->{"usersChecked"} = 0;
$hash->{"startAt"} = $common->getDate("fr_FR", "");
$SIG{INT} = "breakPrg";

while (1) {
$user->check();
$hash->{"t"}++;
}

sub breakPrg {
print "number of boucle ".$hash->{"t"}."\n";
print "started at ".$hash->{"startAt"}."\n";
print "QtyUsers ".$hash->{"QtyUsers"}."\n";
print "usersChecked ".$hash->{"usersChecked"}."\n";
}


-----

user.pm
sub new {
my $condition = 0;
$hash->{"QtyUsers"}++; # each time I instantiate a new user, I
increment this.
}

sub check {


if ($condition eq 1) {
$hash->{"usersChecked"}++;
}

}
 
N

Newsgroups

Le lundi 04 décembre 2006 à 20:10 +0100, Mirco Wahab a écrit :
sub otherSub {
$main::hash{test}++;
}

Thanks, this solution works greats for me ! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top