Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

dear perl monks, i have a constant hash that give a month number according to his abbreviation :
# correspondance map between a month name and his number 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 };
Elsewhere i need to get a reversed hash of the previous, a month abbreviation according to his number. i tried :
my %reverse_month = reverse %{[ MONTH ]} # WRONG
which is i'm afraid not correct. Any idea to solve that ?

Replies are listed 'Best First'.
Re: get a reverse of a constant hash
by Corion (Patriarch) on Jun 11, 2004 at 07:47 UTC

    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.

Re: get a reverse of a constant hash
by borisz (Canon) on Jun 11, 2004 at 07:42 UTC
    To reverse a hash from your constant do:
    my %reverse_month = reverse %{MONTH()};
    Boris
Re: get a reverse of a constant hash
by Joost (Canon) on Jun 11, 2004 at 09:36 UTC
Re: get a reverse of a constant hash
by Anonymous Monk on Jun 11, 2004 at 11:32 UTC

    Thanks all for your answers! i understand now better the constant module.

    Joost: i began to use a variable for holding this MONTH informations, but i feel it would be more "pretty" (if this has a sens :o)) and understable to use a constant, so i change for 'use constant ...'.

    i cannot use Hash::Util as i develop extensions for a Rational product (clearquest), that's embedded with a perl 5.6.1.