A 'constant' is useful - perhaps - because you can't accidentally change it. Method 1 achieves this, whereas method two is no more 'constant' than: my ($min_char, $max_char) = (1,12);

You are free to change the values of your %constant hash anywhere within its lexical scope. The only advantage of your method 2 is the implicit "Don't change these, they are constants" nomenclature of the hash. You can use a sub to generate a 'constant' like this:

sub MIN { return 1 } sub MAX { return 12 }

This generates 'constants' but suffers from the same formatting woes as use constant in that you can't interpolate a sub into a double quoted string. You may like this formatting using printf more:

sub MIN { 1 } # could just as easily be 'use constant MIN => 1;' sub MAX { 12 } printf "x %d - %d x", MIN, MAX;

I have dropped the return as a sub returns the last value it evaluates and I am inherently lazy.

Otherwise use normal lexically scoped variables to make it pretty:

my ($min, $max) = (1,12); print "x $min - $max x";

These are your choices, it's up to you what you prefer. One of the common conventions is to use ALL_CAPS for constants which is important if these constants are actually variables and we are depending on programmer goodwill not to change them. Swings and roundabouts. TIMTOWDI

cheers

tachyon

s&&rsenoyhcatreve&&&s&n\w+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print


In reply to Re: Use constant vs. hashes by tachyon
in thread Use constant vs. hashes by legLess

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.