
ex::constant::vars - Perl pragma to create readonly variables

Using the tie() interface:
use ex::constant::vars;
tie my $pi, 'ex::constant::vars', 4 * atan2( 1, 1 );
tie my @family, 'ex::constant::vars', qw( John Jane );
tie my %age, 'ex::constant::vars', John => 27,
Jane => 'Back off!';
Using the const() function:
use ex::constant::vars 'const'; const SCALAR my $pi, 4 * atan2( 1, 1 ); const ARRAY my @family, qw( John Jane ); const HASH my %age, John => 27, Jane => 'Back off!';
Using import() for compile time creation:
use ex::constant::vars (
'$pi' => 4 * atan2( 1, 1 ),
'@family' => [ qw( John Jane ) ],
'%age' => { John => 27, Jane => 'Back off!' },
);

This package allows you to create readonly variables.
This package tie()s variables to a class that disables any attempt to modify the variables data.
You can store a value in the scalar when it's declared as readonly.
chomp and chop are effectivley disabled for a readonly scalar.
You can store a list in the array when it's declared as readonly.
pop, push, shift, splice and unshift are effictivley disabled for a readonly array.
You can store a record set in the hash when it's declared as readonly.
delete is effictivley disabled for a readonly hash.
const() functionWhen the const() function is imported, so is SCALAR(), ARRAY() and HASH(). These functions allow const() to know what type of variable it's dealing with. const() returns the tied() object of the variable.

This implementation can be slow, by nature. tie()ing variables to a class is going to be slow. If you need the same functionality, and much less of a speed hit, take a look at this: http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2000-05/msg00777.html
The fastest method of declaring readonly variables with this pakcage is to tie() your variables. After that, using the const() function. And lastly, using import() at compile time.
To demonstrate the speed differences:
use Benchmark;
timethese 500000, {
constvars => sub {
tie my $x, 'ex::constant::vars', 'test';
my $y = $x;
},
standard => sub {
my $x = 'test';
my $y = $x;
},
};
Produces:
constvars: 24 wallclock secs (22.55 usr + 0.05 sys = 22.60 CPU) @ 22123.89/s (n=500000) standard: 2 wallclock secs ( 1.12 usr + 0.00 sys = 1.12 CPU) @ 447761.19/s (n=500000)
I wrote it because I believe that it is a solution. I also believe that new ways of implementing this are comming in one form or another.

Casey R. Tweten, <crt@kiski.net>


Copyright (c) 1995 Casey R. Tweten. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.