use constant and hash

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all,

Is there an option to create a constant hash ?

I tried two snippets
This does not compile:
use strict;
use warnings;
my %hash =(1=>2);
use constant A=>%hash;
print A,"\n";

Quoted text here. Click to load it
syntax error at line 5, near "A{"
syntax error at line 6, near "A{"
Execution of aborted due to compilation errors.

and the following does not do the work:
use strict;
use warnings;
my %hash =(1=>2);
use constant A=>\%hash;
print A->,"\n";
print A->,"\n";
print "why do i print this ?\n"

Quoted text here. Click to load it
Use of uninitialized value in print at line 6.

why do i print this ?

I thought afterwards, that the second snippet has no chance to work.
The hash address remains constant even the values changes :-(.

Has anyone another idea ?

Re: use constant and hash

Quoted text here. Click to load it

What exactly do you mean?
(1) a fixed set of keys -- that is, you can neither create nor delete
(2) fixed data -- that is, you can give a value to a given key only
    once, but you can create and delete keys?
(3) both fixed keys and fixed data?
(4) Do you mean recursive constant -- if there's a hash in a value, si
    it locked too?
(5) Do you want the ability to lock and unlock at will?

A CPAN search for
    hash readonly
showed module Readonly.  Damian Conway suggests its use in _Perl Best
Practices_, ch 4, in preference to "use constant".

I did a CPAN search for
    hash locked
and one hit was Hash::Util, which allows various mixtures of those
possibilities.  (Note that lock_keys isn't quite (1): it allows
deleting a key.)  It's somewhat more flexible, but I prefer to know
that something is read-only forever.

Tim McDaniel,

Re: use constant and hash

On Mar 5, 6:24=A0pm, (Tim McDaniel) wrote:
Quoted text here. Click to load it

I would prefer option 4 but option 3 is also good. Readonly looks nice
but the last version is from 2004 (does not have to mean anything).
Hash::Util looks very interesting.


Site Timeline