Hash keys have a bit of a syntactic shortcut. You can omit the quotes for
keys that basically match this regexp (I'm not 100% certain on this):

/^\w$/

So, $hash{FIRST} is ALWAYS evaluated as $hash{'FIRST'}.

If you want to evaluate FIRST to the value "1'st", you must force it:

$hash{FIRST()}
$hash{+FIRST}

I don't like Perl constants for just this reason. There are too many corner
cases that the Perl parser just won't catch. I prefer Readonly, as it uses
normal variable syntax and works as expected.

Scott

On Mon, Feb 28, 2011 at 12:21 PM, Meir Guttman <[email protected]> wrote:

>  Hey folks!
>
>
>
> I discovered the hard way (is there ever an easy way???) that declaring
> constants and then using these as hash keys does not achieve the expected
> (by me, just by me!) results. Rather that using the constant _*value*_ as
> the hash key, it uses the constant _*name*_!
>
> Arrays behave as expected (by me…) though.
>
>
>
> Is that a bug or a feature? Why isn't it consistent: use either the
> constants name in both arrays and hashes or  their value, right?
>
>
>
> Here is a small script to demonstrate the claim. Does your result vary?
>
>
>
> *use strict;*
>
> * *
>
> *use constant FIRST  => "1'st";*
>
> *use constant SECOND => "2'nd";*
>
> *use constant THIRD  => "3'rd";*
>
> * *
>
> *my %hash = (*
>
> *  FIRST  => 'one',*
>
> *  SECOND => 'two',*
>
> *  THIRD  => 'three',*
>
> *  );*
>
> * *
>
> *my @array = (FIRST , SECOND, THIRD);*
>
> * *
>
> *foreach my $key (sort keys %hash) {*
>
> *  print "Hash key: $key, Hash value: $hash{$key}\n";*
>
> *}  *
>
> * *
>
> *print "Array contents: ", join (", ", @array), "\n";*
>
> * *
>
> *# produces:*
>
> *#  Hash key: FIRST,  Hash value: one*
>
> *#  Hash key: SECOND, Hash value: two*
>
> *#  Hash key: THIRD,  Hash value: three*
>
> *#  Array contents: 1'st, 2'nd, 3'rd*
>
>
>
> Regards,
> Meir
>
> _______________________________________________
> Perl mailing list
> [email protected]
> http://mail.perl.org.il/mailman/listinfo/perl
>
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to