in reply to get a reverse of a constant hash
You're close, but not close enough. Let's look at what you're doing:
Your use constant initializes the constant MONTH to a reference to a hash. You want the "inverse" of that hash, which actually happens to exist, as we know that the numbers are unique.
Normally, one can get the inverse of a hash (provided that it exists) by using :
my %forward = ( a => 1, b => 2, ); for (sort keys %forward) { print $_, ":", $forward{$_}, "\n"; }; my %reverse = reverse %forward; for (sort keys %reverse) { print $_, ":", $reverse{$_}, "\n"; };
Your use of the constant complicates matters a bit due to the inner workings of use constant and how perl interprets things. The following code works:
use strict; use warnings; use constant MONTH => { jan => 1, feb => 2, mar => 3, apr => 4, may => 5, jun => 6, jui => 7, aug => 8, sep => 9, oct => 10, nov => 11, dec => 12 }; my %reverse_month = reverse %{ +MONTH }; print $_, ":", $reverse_month{$_},"\n" for sort { $a <=> $b} keys %reverse_month;
Note that I had to specifically use +MONTH, where one would like to see MONTH, because perl thinks that %{MONTH} refers to the (global) variable %MONTH, while it knows that +MONTH refers to the subroutine MONTH, which use constant defines for you.
|
|---|