Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: hash, a troublemaker?

by blokhead (Monsignor)
on May 12, 2004 at 03:38 UTC ( #352639=note: print w/replies, xml ) Need Help??

in reply to hash, a troublemaker?

You can declare the keys as constants as you suggest, or use the lock_keys function from Hash::Util, which comes standard in recent perls. The latter will raise an exception at runtime if an non-existant key is set.

BTW, if you do use constants, an array is more efficient unless only a sparse set of keys are ever used at once:

use constant { K_AGE => 0, K_NAME => 1 }; my @record; $record[K_AGE] = 1001; $record[K_NAME] = 'Doraemon';
The difficulty in making hashes "strict" is just one of the reasons why many people dislike blessed-hashref object implementations.

Update: See also: non-autovivifing hash, how to avoid mis-spelling hash keys?.


Replies are listed 'Best First'.
Re(2): hash, a troublemaker?
by bart (Canon) on May 12, 2004 at 08:50 UTC
    You seem to be reinventing fields, and, dare I say it, pseudo-hashes, a now deprecated feature where you could (or still can) use the hash syntax to access fields in an array.

    Borrowing your example, the internal structure for pseudo-hashes is:

    my $record = [ { K_AGE => 1, K_NAME => 2 }, 1001, 'Doraemon' ];
    And you can access it like:
    print "Name: '$record->{K_NAME}' Age: $record->{K_AGE}\n";
    It just works for 5.6.x, still works for 5.8.3 though with a warning, and this feature will be gone from 5.10.0 on. See the docs on fields for more info, including info on what you really should be using instead.
Re: Re: hash, a troublemaker?
by Doraemon (Beadle) on May 12, 2004 at 06:23 UTC
    (The Hash::Util seems to be the best approach, i think)
    For the 'using constant' approach, I never thought about using arrays. Yes, array ... (why i never thought about it, duh!), looks better. Thanx

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://352639]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2023-09-26 19:56 GMT
Find Nodes?
    Voting Booth?

    No recent polls found