Perl has 2 types of arrays: common arrays and associative arrays which are
called hashes.
In order to get the value of an item from an ordinary array, you need to
specify the index of that array, for example:
my @array = (1, 2, 3);
print $array[1]; #will print "2" (because the indexes start from 0
A hash associates a key to any value and if you want to get the value, you need
to specify its key:
my %hash = (a => 1, b => 2, c => 3);
print $hash{b}; #will print "2"
You can't get the key for a certain value. Say you have the following hash:
my %hash = (a => 1, b => 2, c => 3, d => 2, e => 2);
What's the key for the value "2"?
The keys in a hash are always unique but the values can have duplicates.
If you reverse the hash, the keys become values and the values become keys, so
you will be able to use the value as a key. But if the values have duplicates,
your reversed hash will contain less elements because that hash will contain
unique keys.
In the example above, there would be just a single "2" key and not 3.
So, the question is why do you need to access the keys using their values?
Maybe you want to use an array of arrays like:
my @array = (
['a', 1],
['b', 2],
['c', '3],
['d', 2],
);
To get the "value" for the element with the index 1 you need to do:
my $value = $array[1][1]; #the value "2"
and to get the "key" for the element with the index 1, you can do:
my $key = $array[1][0]; #Will get "b"
I don't know what you need to do... that's why I gave the idea of using arrays
of arrays...
--Octavian
----- Original Message -----
From: richard
To: [email protected]
Sent: Saturday, June 15, 2013 7:12 PM
Subject: perl hash loop: keys() vs values()
Hi
I'm trying to understand the difference between the keys() and values ()
operators. What I'm not getting is why a hash must be reversed to get the key
corresponding to a value? (as stated in perldoc). Can someone explain this
please?
Here is my test script; My perl is freebsd 5.8.9
use warnings;
use strict;
my %hds = ('1', '0C8CB35F', '2', '0C9CB37D');
print "rows: " . scalar keys(%hds) . "\n\n";
my $value;
my $key;
foreach $value (values %hds) {
print "key: $hds{$value} \n";
print "value: $value \n";
}
print "--------------------------- \n";
my %r_hds = reverse %hds;
foreach $value (values %hds) {
print "key: $r_hds{$value} \n";
print "value: $value \n";
}
print "--------------------------- \n";
foreach $key (keys %hds) {
print "key: $key \n";
print "value: $hds{$key} \n";
}
Here is the output:
Use of uninitialized value in concatenation (.) or string at h line 11.
key:
value: 0C8CB35F
Use of uninitialized value in concatenation (.) or string at h line 11.
key:
value: 0C9CB37D
---------------------------
key: 1
value: 0C8CB35F
key: 2
value: 0C9CB37D
---------------------------
key: 1
value: 0C8CB35F
key: 2
value: 0C9CB37D
--
regards, Richard
--
[email protected]