Nov 10, 2009, 6:09 AM
Post #3 of 7
Re: [DivyaG] 'constant' in perl
[In reply to]
Can we define any variable as constant in perl (just like const in C and Java), so that its value cannot be modified throughout the program?
There are two techniques to get unmodifiable values in Perl: `use constant;` and `use Readonly;`
The pragmatic constant is part of the standard Perl installation and is available to any script. It creates a sub that returns the value. It can be used anywhere a sub can.
perl -e 'use constant PI=>atan2(0,-1); print PI, "\n"'
Running the deparser on it, you can see the sub. You can also see that the compile phase replaces the sub with the value for faster execution.
perl -MO=Deparse -e 'use constant PI=>atan2(0,-1); print PI, "\n"'
Readonly is a module available from CPAN: http://search.cpan.org/~roode/Readonly-1.03/Readonly.pm
What is does is tie into the variable and disables its ability to change. This adds some execution overhead every time the variable is used.
It biggest drawback is that Readonly must be installed on every system where the script runs.
I love Perl; it's the only language where you can bless your thingy.
Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.
Get Markup Help. Please note the markup tag of "code".