ken Foskey wrote:
> On Sat, 2008-04-05 at 00:37 +0800, Jeff Pang wrote:
>> On Fri, Apr 4, 2008 at 11:42 PM, <[EMAIL PROTECTED]> wrote:
>>> use constant PART_NUMBER => 'P/N';
>>>
>>> print PART_NUMBER;
>>>
>>> The above prints, "P/N", as I would expect. Later in the script I
>>> want to access a hash value using the constant like this:
>>> my $part = $parts{ $key }{ PART_NUMBER }; <- this doesn't work, but
>> because the hash think "PART_NUMBER" is a key name instead of a constant.
>> to avoid this confusion, add a "+" before the constant,
>>
>> my $part = $parts{ $key }{ +PART_NUMBER };
>
> Is there any real advantage of
>
> use constant PART_NUMBER => 'P/N';
> over
> my $PART_NUMBER = 'P/N';
>
> Yes I know that it can be modified but conventions such as upper case
> constants can almost remove that problem.
- Conventions don't work. Imagine someone in a team using $PI and
getting the error
Global symbol "$PI" requires explicit package name
What do they do? They write a line that says
my $PI = 31.4;
and the error goes away. Except that it doesn't.
- It's not a nice thing to do. Constants are constants, variables are
variable.
- Optimization. If I write
use constant PART_NUMBER => 'P/N';
my $label = PART_NUMBER.'O';
it will be compiled as
my $label = 'P/NO';
but if I wrote
my $PART_NUMBER = 'P/N';
my $label = $PART_NUMBER.'O';
I get exactly that, and the concatenation will be done at run time,
regardless of the supposed constancy of the expression. Similarly, if
I write
use constant DEBUG => 0;
if (DEBUG) {
print "$_\n" foreach @data;
}
the entire block will vanish at compile time, whereas the equivalent
using an invariant variable will make the Perl interpreter do the
test.
There may well be more good reasons that don't come to my mind; but
aren't those sufficient?
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/