Look at the following snippet of code (do not run it yet).

#!/usr/bin/perl -w use strict; use constant BAR => 3; use constant FOO => 2, BAZ => 1, JAPH => 0; print BAZ,$/;

What happens?

If you said that it outputs the value 1, then you would be wrong. Why? No comma allowed after filehandle at constant.pl line 5. Say what? That's right. There is no constant named BAZ so Perl reads it as a filehandle.

Replace print BAZ,$/; with print +(FOO)[BAR],$/;. Now what happens?

If you said outputs the string "JAPH", then you would be right. Why? use constant FOO => 2, BAZ => 1, JAPH => 0; creates a constant named FOO containing the array list (2, 'BAZ', 1, 'JAPH', 0). Don't believe me? See what happens when you add this to the end of the script:
foreach (FOO) { print $_,$/; }

None of this should be a surprise to any one who is familiar with the constant pragma. Normally constants must be declared one per statement. You may also "define multiple constants in a single statement by giving, instead of the constant name, a reference to a hash where the keys are the names of the constants to be defined. Obviously, all constants defined using this method must have a single value."

use constant { FOO => 3, BAR => 2, BAR => 1, JAPH => 0, };
So if you need a constant to contain an array or a hash, it must have it's own declaration statement.

Updated: I posted this in the hope that it may shed some additional light on the subject. Thank you PodMaster.


In reply to constant confusion by Mr. Muskrat

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.