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."
So if you need a constant to contain an array or a hash, it must have it's own declaration statement.use constant { FOO => 3, BAR => 2, BAR => 1, JAPH => 0, };
Updated: I posted this in the hope that it may shed some additional light on the subject. Thank you PodMaster.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: constant confusion
by PodMaster (Abbot) on Apr 23, 2003 at 14:55 UTC | |
|
Re: constant confusion
by perrin (Chancellor) on Apr 23, 2003 at 15:31 UTC | |
|
Re: constant confusion
by crenz (Priest) on Apr 23, 2003 at 16:19 UTC | |
by Mr. Muskrat (Canon) on Apr 23, 2003 at 16:22 UTC | |
by Abigail-II (Bishop) on Apr 23, 2003 at 20:31 UTC | |
by Aristotle (Chancellor) on Apr 26, 2003 at 03:16 UTC | |
by crenz (Priest) on Apr 23, 2003 at 16:27 UTC | |
by Aristotle (Chancellor) on Apr 26, 2003 at 03:04 UTC |