develooper Front page | perl.perl5.porters | Postings from May 2000

Re: Proposed pragma: readonly - summary

From:
Mark Summerfield
Date:
May 22, 2000 12:22
Subject:
Re: Proposed pragma: readonly - summary
Message ID:
392987AF.793C852@queenwood.screaming.net
Ian Phillipps wrote:
[snip] 
> Hmm... I've always (well, since perl 5) done this:
>         *pi = \3.14159;
> You can then read $pi, but not alter it. No XS, modules or tying required.
> 
> ~ % perl -we '*pi=\3.14159;print "pi=$pi\n"; $pi+=1; print "pi now $pi\n";'
> pi=3.14159
> Modification of a read-only value attempted at -e line 1.
> 
> I just did a Benchmark and the speed of reading is identical with a
> "normal" global scalar.

The above is what my readonly pragma does, except it declares &
assigns in one step so instead of the two steps:
	use vars '$pi' ; *pi = \3.142 ; 
you can simply:
	use readonly '$pi' => 3.142 ; 
and that's it.
I'm sure you can guess what the following based on your examples will
output...

#!/usr/bin/perl -w
use strict ;
use vars qw( $pi ) ; # I like strict
*pi = \3.14159 ;
print "$pi\n" ;
# Somewhere deep in the same file far far away...
*pi = \'splat' ;
print "$pi\n" ;

The one-liner is the same:
# perl -we'*pi=\3.142;print "$pi\n";*pi=\"splat";print "$pi\n"'

But the cases that I'm really interested in are where you want to export
constants and be sure that they can't be messed up:

# File: Try.pm
package Try ;
use strict ;
use vars qw( @ISA @EXPORT $pi ) ;
use Exporter() ;
@ISA = qw( Exporter ) ;
@EXPORT = qw( $pi ) ;
*pi = \3.14159;
print "Try loaded: $pi\n" ; 
1 ;

# File: try
#!/usr/bin/perl -w
use strict ;
use vars qw( $pi ) ;
use Try ;
# Far away...
*pi = \'splat' ;
# Further away still...
print "$pi\n" ;

_______________________________________________
Mark Summerfield       http://www.perlpress.com




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About