in reply to Dynamic hash keys

Is there any way of changing BOTH 'that' to 'them'?

Sure, just do two assignments. Or in the case of hash keys, delete the old one, and add the contents back in with a new name.

But the real answer is that you should try to avoid redundancy in mutable data structures. Depending on your actual problem, there is a good chance that there's a better way to build your data structure, but without knowing what kind of operations you want to do with them, we can't tell.

You can also read up on normalization forms. That's a concept that's often used in the area of databases, but it (partially) applies to any mutable data structure.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^2: Dynamic hash keys
by markdibley (Sexton) on Aug 17, 2010 at 10:33 UTC
    Thanks for the reply. I don't think my requirements are particularly unusual, just that I am not doing it right.

    I have a sample that has multiple tests. When a test is assigned to a sample it has a temporary id. After it is verified it is given a permanent id.

    I want to put the tests in the hash indexed by their ids for quick retrival by their id and change the id when necessary.

    Did I mention that sample and test are objects (kind of - as I don't have any OO training they are quite quasimodo in their OOness). Which means if I normalise and the test id is set in the sample object then I cannot access that id from the test object.

    I am probably making things too hard for myself. I have read some of the OO tutorials, but when I get to the bits that I don't know and (definitely) need the language of the tutorial suddenly becomes "encrypted". I'll keep trying.

    Thanks again

      Rather than changing the ID, why not give the test another attribute ('validated' for example)?

      Then you don't have to worry about collisions with pre-existing IDs when validating.

      foreach my $currentTestID (keys %$tests) { $tests->{$currentTestID}{validated} = validate($tests->{$currentTe +stID}); }
      sub doValidatedTests { my $tests = shift; doTest($_) foreach ( grep {$tests{$_}{validated}} keys %$tests ); }

      When the IDs don't change, you're free to tell the test object what its ID is when you create it, and it will be valid until you drop the test from your hash and the test itself gets garbage collected shortly thereafter.

      One solution is to keep separate hashes for objects with temporary id, and for those which are are confirmed.

      When one object is verified, you delete it from the hash that is keyed by temporary ID, assign it its new, permanent ID, and insert it into the hash that holds on the confirmed objects.

      Perl 6 - links to (nearly) everything that is Perl 6.