On 3/22/12 Thu Mar 22, 2012 2:23 PM, "Chris Stinemetz" <chrisstinem...@gmail.com> scribbled:
> I would like to use the number on the left as a key in a hash and use > the number on the right as the value pair to the key. Then print the > values for each hour that have the same key. Maybe this is a good > example for an array of hashes, but I not real sure how to begin. Any > help is greatly appreciated. > > Below is the input data: > > Hr 12 > 0001 2 > 0002 3 > 0003 1 > Hr 13 > 0001 2 > 0002 3 > 0003 1 > Hr 14 > 0001 2 > 0002 3 > 0003 1 > > Desired output below: > > 12 13 14 > 0001 2 2 2 > 0002 3 3 3 > 0003 1 1 1 I would suggest using a hash-of-hashes. You have a two-level key: the first (primary) key is the hour value: 12, 13, 14. The second (-ary) key is the number from the left-hand column. The value is the number from the right-hand column. So read the file, save the hour keys in a variable (e.g. $hour), extract the two numbers (e.g. $left, $right), and store the values in a two-level hash: $hash{$hour}{$left} = $right; Then, when you have read the entire file, print the data in your desired format. The printing will be a little tricky as you are "inverting" your data with respect to the keys, so you can't do a simple two-level traversal over the nested hashes and print as you go. If all you want is to print as shown, then you can invert the importance of the keys and use this instead: $inverted_hash{$left}{$hour} = $right; Then you can traverse the "left" numbers and print the "hour" values for each one. Sometimes the trick for effective programming is defining the right data structure. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/