- Perl ›
- builtin functions ›
- here
keys function - get all keys in the hash
You can use the keys function to get all the keys in hash. The order of the got keys is indefinite.
# Get all keys my @keys = keys %hash;
If you pass hash reference as an argument, you need to dereference it.
# Get all keys. For hash reference. my @keys = keys %$hash;
Output all hash keys and values
Try to output all the keys and all the values of the hash using the keys function.
# Sort by key dictionary order and output my $scores = {Ken => 1, Mike => 2, Rika => 3}; for my $person (sort keys %$scores) { print "$person: $scores->{$person}\n"; }
The output result is as follows.
Ken: 1 Mike: 2 Rika: 3
The keys obtained with the keys function are in an indefinite order. When combined with sort function, it can be output in a stable order.
# Sort by key dictionary order and output my $scores = {Ken => 1, Mike => 2, Rika => 3}; for my $person (sort keys %$scores) { print "$person: $scores->{$person}\n"; }
Furthermore, if you combine it with reverse function, you can output in the reverse order.
# Sort by key dictionary order and output my $scores = {Ken => 1, Mike => 2, Rika => 3}; for my $person (reverse sort keys %$scores) { print "$person: $scores->{$person}\n"; }
Get all hash values
If you just want to get all the hash values, you can use values function.
my @values = values %hash;
Get key/value pairs in order
If you want to get the key/value pairs in order, you can use the each function.
# Get (key, value) pairs in order my %age = (Ken => 19, Mike => 34); while (my ($name, $age) = each %age) { ... }
while statement is used to retrieve the key/name pairs in order.
There are similar functions such as keys function, values function, and each function, but it is recommended to use the keys function for hash processing. The keys function has good performance and is very easy to use among the three.