Dan Muey wrote: > > Howdy, > > I read in an earlier email that some people put _ in front of > variables/function/etc to show that they are "important and should be > handled by the program only" and it said that some "modules enforce this" > > I guess what I'm getting at is: > > If my module exports variables can I make it so they can't be changed? > > IE > > use MyStuff qw($_joe $_mama); # now they should have $_joe and $_mama > exported from the module. > > print "$_joe $_mama\n"; # ok > my $joe = $_joe; # ok > $joe =~ s/\W//g; # ok > $_joe = "new value"; # bad - not allowed - maybe give warning? > $_mama =~ s/\W//g; # bad - not allowed - maybe give warning? > > If so hwo do I do it or what module protects its variables in this way so > I can look at it's code for an example or documentation???
a lot of people have suggested using closures which is nice. another appoach is to use tie. simple example: package ConVar; sub TIESCALAR{ my $class = shift; my $value = shift; return bless \$value => $class; } sub FETCH{ ${$_[0]} } #-- #-- variable that can't be changed #-- sub STORE{ warn("modification is not allowed\n") } 1; __END__ package MyModule; use Exporter; use ConVar; our @ISA=qw(Exporter); our @EXPORT_OK = qw($var1 $var2); #-- export read only #-- #-- your module implementing the read only variable #-- tie our $var1,'ConVar',5; tie our $var2,'ConVar',6; 1; __END__ #!/usr/bin/perl -w use strict; use MyModule qw($var1 $var2); #-- #-- testing the read only variable #-- $var1 = 7; $var2 = 8; print "$var1\n"; print "$var2\n"; __END__ prints: modification is not allowed modification is not allowed 5 6 notes: * the code is, generally speaking and imo, cleaner. * user notice no differences (except when they start benchmark their script) whether $var1 has magic behind it or not. * you can tie anything (array, hash ref, or another object) behind the simple scalar interface and it still looks like a simple variable to the users of your module. * it's slower than the other method. probably 10 times * it's not very secure. for example: my $g = tied $var1; $$g = 10; print "$var1\n"; #-- $var1 is now 10. other tricks and readings can be found at: perldoc -f tie perldoc perltie david -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]