http://qs1969.pair.com?node_id=405812


in reply to Introduction to anonymous arrays and hashes

If I understand your current approach correctly, you have a bunch of meta tags and each tag has a set of data associated with it (value, char count, etc). When you said you're "creating a mess of hashes on the fly", it sounds like you're either using symbolic references (don't do that) or doing something like this:

%title = ( value => 'Welcome to my website!', char_ct => 22, word_ct => 4, repeat_ct => 1 ); %keywords = ( value => 'candy, food, pop, candy cane, soda, caffeine', char_ct => 31, word_ct => 5, repeat_ct => 2 ); etc...
I think what you're looking for here is a hash of hashes (which is actually a hash of hash references). You could combine the %title and %keywords hashes from above into a single hash:
%tags = ( title => { value => 'Welcome to my website!', char_ct => 22, word_ct => 4, repeat_ct => 1 }, keywords => { value => 'candy, food, pop, candy cane, soda, +caffeine', char_ct => 31, word_ct => 5, repeat_ct => 2 } );
Now you've got a single hash to store all your data in, and you don't need to worry about creating hundreds of individually declared hashes.

Getting data into this HoH (and accessing it) is simple. Instead of doing:

$title{value} = 'Welcome to my website!';
do this:
$tags{title}{value} = 'Welcome to my website!';
New inner (e.g., value) and outter (e.g., title) keys can be added at will.

Keep in mind that the value of $tags{title} is actually a reference to another hash. If you wanted to use the hashrefs instead of accessing the data directly (e.g., passing it to a subroutine), you would dereference it like this:

( $num_chars, $num_words ) = count_chars_words( $tags{title} ); sub count_chars_words { my ( $hashref ) = @_; my $value = ${ $hashref }{value}; # count stuff and return }
Since all of the inner hashes were set up the same, the subroutine doesn't need to know (or care) about which hashref it gets, all it knows is that there is a key named 'value' in the hash.

What if you want to add an array to the HOH? Let's add a new key to the inner hash, whose value is an arrayref:

$tags{keywords}{val_list} = [ ( split( ', ', $tags{keywords}{value} ) +) ]; print ${ $tags{keywords}{val_list} }[2]; # pop

References are very powerful and provide nearly unlimited flexibility in your data structure. They are well worth learning. The obligatory reference list: perlref, perlreftut, and perldsc.

HTH.