in reply to Re^2: Need advice on checking two hashes values and keys
in thread Need advice on checking two hashes values and keys
(I'd suggest that you keep posting to this thread as long as you're working on the same problem, unless people stop responding to it.)
Ok, let's say you want to create a hash of two-element arrays, with the hash keys being the Italian numbers, each one pointing to a reference to a two-element array holding the Spanish and French numbers, in that order. Then as you're going through the first loop (Italian = Spanish), you need to insert the Spanish numbers as the first element of an array rather than a simple value:
$hash{$italian} = [ $spanish ];The square brackets return a reference to an array, which is a scalar that can be stored as a value in the hash. So now it looks like this, with references to one-element arrays as the values:
$hash = ( uno => [ 'uno' ], due => [ 'dos' ], # and so on );
Then in the second loop, you need to add the French numbers to the arrays corresponding to their matching Italian hash keys. There are two ways you could do this:
# by assigning directly to the second element of the sub-array $hash{$italian}[1] = $french; # or by dereferencing the sub-array pointed to by the hash value # and pushing the new value onto the end of that array push @{$hash{$italian}}, $french; # Either way, you'll end up with: $hash = ( uno => [ 'uno','un' ], due => [ 'dos','deux' ], # and so on );
Then when you're ready to print them out, you loop through the keys of the hash, printing the key and the elements of the sub-array as you wish:
for my $key (keys %hash){ print $key, ' => ', join ' , ', @{$hash{$key}}; # dereference sub-ar +ray print "\n"; }
The trick is keeping track of what level of the structure you're dealing with, and getting the sigils (and arrows, if necessary) right for pointing to the right things, whether values or references.
Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Need advice on checking two hashes values and keys
by perlynewby (Scribe) on Jun 04, 2015 at 23:23 UTC | |
by aaron_baugher (Curate) on Jun 05, 2015 at 02:01 UTC | |
by Anonymous Monk on Jun 09, 2015 at 18:41 UTC | |
by aaron_baugher (Curate) on Jun 09, 2015 at 20:52 UTC | |
by Anonymous Monk on Jun 10, 2015 at 00:15 UTC | |
|