Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Creating constant arrays or hashes

by Boogman (Scribe)
on Aug 02, 2000 at 20:14 UTC ( [id://25759]=perlquestion: print w/replies, xml ) Need Help??

Boogman has asked for the wisdom of the Perl Monks concerning the following question:

Using typeglobs it is possible to create constant scalars by saying something like *PI = \3.14159; I haven't been able to find any similar way to create constant arrays or hashes. Since taking a reference to a list is just the same as having a list with all the elements references, *LIST = \( 'a', 'b', 'c' ); is the same as *LIST = ( \'a', \'b', \'c' ); and just makes $LIST a constant to 'c' and doesn't change @LIST at all. Using an anonymous array instead of a reference to a list doesn't work either cause anonymous arrays are lvalues and not constants...

Does anyone know of a way to make constant array or hash variables?

Replies are listed 'Best First'.
Re: Creating constant arrays or hashes
by jlistf (Monk) on Aug 02, 2000 at 20:20 UTC
    one of the best ways to make constants in general is using prototyped subroutines (in fact thats one of the only things prototypes are good for). so:
    sub PI () { return 3.14 }
    or:
    sub constantArray () { return ( 4, 5, 6) }
    that should do it.

    jeff
RE: Creating constant arrays or hashes
by Adam (Vicar) on Aug 02, 2000 at 20:47 UTC
    You can also use the "constant" module:
    use constant SCALAR_CONST => 3.14159265; use constant ARRAY_CONST => ( 'This', 'is', 'fun' ); use constant HASH_CONST => ( pi => 3.14159265, c => 299_792_458 ); # m/s #etc.
    Which actually just creates convenient sub routines for you. ( I prefer this method because it is a little more explicit, plus it is self documenting. )
Re: Creating constant arrays or hashes
by BlueLines (Hermit) on Aug 02, 2000 at 22:04 UTC
    don't forget about Const, which is similar to what you suggested. This and other interesting tidbits can be found in this node.

    BlueLines

    Disclaimer: This post may contain inaccurate information, be habit forming, cause atomic warfare between peaceful countries, speed up male pattern baldness, interfere with your cable reception, exile you from certain third world countries, ruin your marriage, and generally spoil your day. No batteries included, no strings attached, your mileage may vary.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://25759]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-28 11:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found