in reply to What is the difference between the constant construct in Perl and the Readonly construct in Perl?
The Readonly module doesn't work as you demonstrate. The code you provided:
use Readonly PI => 3.141593;
will generate the following error message:
Readonly version 3.14 required--this is only version 1.03 at C:/Perl/l +ib/Exporter/Heavy.pm line 121. BEGIN failed--compilation aborted at mytest.pl line 5.
You probably mean to say the following:
use Readonly; Readonly my $PI => 3.141592654; print "$PI\n";
In which case, it should be immediately apparent what the differences between use constant and Readonly are. For one thing, the Readonly function creates a readonly scalar, hash, or array. These entities can be lexically scoped or they can be package globals. And they retain most of the characteristics of an ordinary Perl variable. They have a sigil ($, %, or @), and interpolation rules follow those of any ordinary Perl variable. These enhancements over the tired use constant pragma are significant, and solve issues that diminished the usefulness of the constant pragma.
If you were to try to modify that readonly variable, as in $PI = 3.5;, Readonly will die with an error message like this: Modification of a read-only value attempted at test.pl line 13.
There are a few other pros to using Readonly, and a Con also (having to do with speed), which can be improved upon by also installing Readonly::XS. Have a look at the documentation for Readonly, and I think you'll see. It provides a great list of pros and cons, and also describes the implications of installing the XS companion module. I was turned on to the module by reading Perl Best Practices.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What is the difference between the constant construct in Perl and the Readonly construct in Perl?
by demerphq (Chancellor) on Jul 07, 2006 at 13:07 UTC |