On Mon, 28 Jun 2004, Martin Adler wrote:
> What can I "use" to make the following program work as I want it to?
>
> #!/usr/bin/perl -w
> use strict;
> use constant N => 17 ;
> my %x ;
> $x{N} = 25 ; # who wants to write $x{(N)} = 25 all the time?
> print keys %x ;
>
> The output is "N", so Perl apparently interprets $x{N} as $x{"N"}.
> But how can I tell it to interpret constants as their (constant)
> value?
> I want Perl to interpret $x{N} as $x{17}.
>
> One of the goals of perl is "to make easy tasks easy and difficult
> tasks possible". It seems to me that it is POSSIBLE to use constants
> as hash keys (e.g.: $x{ (N) }), but it does not look EASY.
>
> Or what else should I do?
Perl is trying to make something easy. It's just not what you want to be
easy in this case. Perl's auto-quoting is taking over here, which makes
it easy for the vast majority of cases, when we want $x{N} to mean
$x{'N'}, instead of the remarkably few cases when we want $x{N} to mean
$x{(WhateverValueConstantNRepresents)}.
You have three basic options:
write $x{N()} instead of $x{N}
write $x{+N} instead of $x{N}
use the ReadOnly module from CPAN instead of the constant pragma. This
defines constants that look like Perl variables instead of C Macros:
use ReadOnly $N => 17;
$x{$N} = 25;
Paul Lalli
|