I have a situation where I have 3 different values for each key. I have to print the data like this:
K1 V1 V2 V3 K2 V1 V2 V3 … Kn V1 V2 V3
Is there any alternate efficient & easier way to achieve this other that that listed below? I am thinking of 2 approaches:
-
Maintain 3 hashes for 3 different values for each key.
Iterate through one hash based on the key and get the values from other 2 hashes
and print it.Hash 1 - K1-->V1 ... Hash 2 - K1-->V2 ... Hash 3 - K1-->V3 ...
-
Maintain a single hash with key to reference to array of values.
Here I need to iterate and read only 1 hash.K1 --> Ref{V1,V2,V3}
EDIT1:
The main challenge is that, the values V1, V2, V3 are derived at different places and cannot be pushed together as the array. So if I make the hash value as a reference to array, I have to dereference it every time I want to add the next value.
E.g., I am in subroutine1 – I populated Hash1 – K1-->[V1]
I am in subroutine2 – I have to de-reference [V1], then push V2. So now the hash
becomes K1-->[V1 V2], V3 is added in another routine. K1-->[V1 V2 V3]
EDIT2:
Now I am facing another challenge. I have to sort the hash based on the V3.
Still is it feasible to store the hash with key and list reference?
K1-->[V1 V2 V3]
It really depends on what you want to do with your data, although I can’t imagine your option 1 being convenient for anything.
Use a hash of arrays if you are happy referring to your
V1,V2,V3using indexes 0, 1, 2 or if you never really want to handle their values separately.or, of course
As an additional option, if your values mean something nameable you could use a hash of hashes, so
or
Finally, if you never need access to the individual values, it would be fine to leave them as they are in the file, like this
But as I said, the internal storage is mostly dependent on how you want to access your data, and you haven’t told us about that.
Edit
Now that you say
I think perhaps the hash of hashes is more appropriate, but I wouldn’t worry at all about dereferencing as it is an insignificant operation as far as execution time is concerned. But I wouldn’t use
pushas that restricts you to adding the data in the correct order.Depending which you prefer, you have the alternatives of
or
and clearly the latter is more readable.
Edit 2
As requested, to sort a hash of hashes by the third value (
heightin my example) you would writeor, if the data was stored as a hash of arrays
The output for both scripts is identical