Click to See Complete Forum and Search --> : YaR: private variables in perl


TheLinuxDuck
01-24-2001, 05:06 PM
I came across this tres qool way to make private data in a perl script. If you define variables inside a block, and also define subs inside that same block, the variables will be private to that block, but the subs will be global. This way, you can alter the variables indirectly, without ever having actual access to them..

I thought it was pretty qool. http://www.linuxnewbie.org/ubb/smile.gif

#!/usr/bin/perl -w
use strict;
use warnings;
#
{
my($userName,@arrayList);
sub changeUserName
{
$userName=$_[0];
}
sub showUserName
{
return $userName;
}
sub addArrayItems
{
push @arrayList, @_;
}
sub showArrayList
{
my($retVal);
$retVal.="$_ " for(@arrayList);
return $retVal;
}
}
#
# Uncomment these two lines to receive a
# compile time error
#
# print "$userName\n";
# print "@arrayList\n";
changeUserName("Jeffrey");
print showUserName()."\n";
addArrayItems("dingle","flumpy","bacteria");
print showArrayList()."\n";
exit;


http://www.linuxnewbie.org/ubb/smile.gif

------------------
TheLinuxDuck
I have a belly button.
:wq

YaRness
01-24-2001, 05:26 PM
yeah, i read something earlier that woulda implied that was possible. basically local variables kinda keep on living as long as there's something referencing them (in this case, a later call to the same subroutine), even though, if it were done properly, after the block they should be dead. not to mention you shouldn't be able to access those subroutines either. i'd be afraid to use that, cuz it might get fixed later. and it's bad programming.

BUT since it's perl, i'm playing with it anyway for laughs. i can't seem to get it to work with my package though (put all my subs and junk in a block, but i can still explicitly reference $yarobj->{'NAME'}). well i'll take it home with me and play with it, i'm already at work late as it is. bbiab.

------------------
"Assembly of Japanese bicycle require great peace of mind."
Registered Linux User #188285 http://counter.li.org/