in reply to hash, a troublemaker?

Why are you using a hash in this case? It looks like you are using it where one would use a struct in C. Now, either of two things could be the case: you just have a single hash with this role, or it's one of many. In the first case, you can avoid the hash altogether, and just use variables, $name, $age, etc. If you have more of them, just turn them inside-out. Say you would normally have %person1, %person2, %person3, etc, each with an age, a name, and perhaps more, something like:
my (%person1, %person2, %person3, ...); $person1 {name} = "..."; $person1 {age} = ...; $person2 {name} = "..."; $person2 {aeg} = ...; # Oopsie. $person3 {name} = "..."; $person3 {age} = ...;
Instead of hashes for the entities, and attributes as the keys, make hashes for the attributes, using the entities as attributes - just make sure the entities are unique.
my (%age, %name); my $entitie_count = 0; my $person1 = ++ $entitie_count; my $person2 = ++ $entitie_count; my $person3 = ++ $entitie_count; $name {$person1} = "..."; $age {$person1} = ...; $name {$person2} = "..."; $aeg {$person2} = ...; # Compile time error with use strict. $name {$person3} = "..."; $age {$person3} = ...;


Replies are listed 'Best First'.
Re: Re: hash, a troublemaker?
by flyingmoose (Priest) on May 12, 2004 at 14:11 UTC
    This is rather ugly, you have a set of lookups for various values without correlation to structures, while the opening example does have problems of hash abuse with misspelling, I'd MUCH rather see field identifiers as constants and an HoH as a datastructure rather than having unaffiliated fields.

    i.e. $records{$person}{$K_AGE}

    That way you keep records grouped. Since Perl doesn't have real structures of any merit, the next logical step is to go to an OO representation and use functions/etc (maybe one of those MethodMaker deals) to prevent accidental typos.

    At minimum, the Hash::Util method provides locking while preserving the logical representation of the data (edit: and clean Data::Dumper dumpability!).

    Keeping fields seperated without context, IMHO, is the worst thing you can do.

      This is just the same technique I use for InsideOut objects, so going to an OO model wouldn't be much of a change for me. ;-). And if you use functions, you can still make typos in the functions when you access the attributes - which is why I developed InsideOut objects in the first place.


        yep, that's a lot cleaner when the collections of fields start having namespace...
      Sorry Abigail-II :)
      I agree with flyingmoose. Related fields should be grouped together, with a name represent these related data. At this point i strongly support the reference mechanism, but somehow, we need to create a reference that have information about the data that it's pointing to.