From: Paul Lalli <[EMAIL PROTECTED]> > On Jun 8, 7:33 am, [EMAIL PROTECTED] (Alok Nath) wrote: > > What is the convention used to declare constants in perl ? > > In C we declare constant type in Capital letters , not sure > > how its in perl. > > There is a 'constant' pragma in Perl that you can use: > use constant PI => 3.14; > > but it is "better" these days to use the Readonly module, available on > the CPAN. They have several advantages over constants: > 1) They can be defined lexically - constants are globals (because > they're implemented as subroutines) > 2) They interpolate into strings, because they're real variables > 3) You can define Readonly hashes and arrays as well as scalars. > > So many people would prefer you abandon the first example I gave, and > replace it with: > use Readonly; > Readonly my $PI => 3.14; > > Paul Lalli
Everything has it's pros and cons. 1) The constant pragma is already installed with any Perl 5.004 or newer, while you have to install Readonly.pm 2) The constants created by the constant pragma are actually known and believed to be constant in compiletime and the optimizer may use that knowledge. Compare perl -MO=Deparse -e "use constant FOO => 0; expensive() if FOO; print 1;" ==> use constant ('FOO', 0); '???'; print 1; and perl -MO=Deparse -e "use Readonly; Readonly my $FOO => 0; expensive() if $FOO; print 1;" ==> use Readonly; Readonly my $FOO, 0; expensive() if $FOO; print 1; or perl -MO=Deparse -e "use constant X => 12414; print X*78.7;" ==> use constant ('X', 12414); print 976981.8; and perl -MO=Deparse -e "use Readonly; Readonly my $X => 12414; print $X*78.7;" ==> use Readonly; Readonly my $X, 12414; print $X * 78.7; As you can see with "use constant" the optimizer has a chance to remove inaccessible code or precompute some constant dependent expressions, with Readonly it can't. Which may or may not matter, but you should be aware of that. Jenda P.S.: The -MO=Deparse tells perl to parse, compile and optimize the code and then instead of executing it, convert it "back" to readable code and print. ===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz ===== When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/