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.


In reply to Re: get a reverse of a constant hash by Corion
in thread get a reverse of a constant hash by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.