in reply to Storing an indeterminate number of hash keys in a variable

This feels like the wrong solution to the problem as the results are very messy. This seems like a good situation for a struct type solution:

use strict; use warnings; # make a little mini class for your records use Class::Struct Record => [title => '$', rule_severity => '$', rule_ +weight => '$' ]; my %data_hash = (); my @data_array = (); $data_hash{first_key} = new Record; $data_hash{second_key} = new Record; # instead of pushing a text string of keys, just push field to access push(@data_array, 'title'); push(@data_array, 'rule_weight'); # some code later changes the hash $data_hash{first_key}->title('Mr. President'); $data_hash{first_key}->rule_weight(100); $data_hash{second_key}->title('Emperor'); $data_hash{second_key}->rule_weight(1000); # want to access it from your array for my $key (sort keys %data_hash) { for my $field (@data_array) { print "My data is (".$data_hash{$key}->$field.")\n"; } }

Output:

C:\tmp>tmp.pl My data is (Mr. President) My data is (100) My data is (Emperor) My data is (1000)

Replies are listed 'Best First'.
Re^2: Storing an indeterminate number of hash keys in a variable
by tj_thompson (Monk) on Jul 08, 2011 at 22:42 UTC
    Wish you could edit comments :) I mean that storing the keys of a hash seems messy, thus the struct solution.

      In fact you can. Just click on the title of your reply (or this link, in this case), scroll down until you see the text box, edit its content, hit the update button and you're done. It's as simple as it sounds :)

      Edit:To prove my point, and to also contribute my two cents to the discussion at hand, wind's solution above is along the lines of what I would've tried.

        When sufficiently tired, I've also been unable to figure out how to edit my own node. ;-) But thanks for pointing out how to the OP. :-)

        HTH,

        planetscape
        Hey, thanks! Very handy on the comment editing. I realized after my post that you don't seem to know the number of fields you will have prior to creating them, so my solution wouldn't work for you any way. Reading comprehension fail on my part :)