Since hash keys are strings, the question is really how can you avoid one-off errors when a string appears multiple times in a piece of code. Two solutions occur to me:

  1. At the head of your code you could predeclare all your desired keys, either in an array or a series of scalars. In that way, you could directly harness strict to keep your keys in line.
  2. A solution I think is a bit more elegant would be using constants to assign your allowed keys at start. Something like:

    #!/usr/bin/perl use strict; use warnings; use constant {KEY_1 => 0, KEY_2 => 1}; my %hash = (KEY_1() => 5, KEY_2, 7); print $hash{KEY_1()}; print @hash{KEY_1, KEY_2};

    Note that constants are really subroutines (Thanks for the CB help tye), so trying to access them using $hash{KEY_1} will fail, though you could build in a little resilience by making the value of KEY_1 equal to 'KEY_1'.


In reply to Re: strict and hashrefs by kennethk
in thread strict and hashrefs by danmcb

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.