Hi perl-diddler,
Isn't the stuff in brackets an anonymous hash? Isn't the ordering of hashes strictly not guaranteed by default?
Yes and yes.
So how could that work, since the numbers and the labels in the hash, it would seem, should end up in a random order?
Note that "random order" does not mean this:
use List::Util qw/shuffle/; my @order = shuffle qw/ continue 0 next 1 redo 2 last 3 /;
What it means is this:
my @keyorder = shuffle qw/ continue next redo last /;
So constant will always define four subs, which return the value associated with each key in the hash. It is equivalent to the following code; the order in which the subs are defined does not matter. (By the way, I think that defining subs with the same name as those Perl builtins is likely to cause confusion later.)
sub continue () { 0 } sub next () { 1 } sub redo () { 2 } sub last () { 3 }
I know the following would fail (because the RHS of the 'our $clist' won't be done at compile time):
Correct, but this would work:
our $clist; BEGIN { $clist = {continue=>0, next=>1, redo=>2, last=>3 } } use constant $clist;
But how is it that this seems to always work:
If I understand mem correctly, it's essentially doing the same thing as the code with the BEGIN block above. Also, remember that use Module LIST is exactly equivalent to BEGIN { require Module; Module->import( LIST ); }.
Is it that compile-time hashes are not randomized?
No, AFAIK Perl always iterates over hashes in a random order. No, you should always treat Perl hashes as being in a random order. Also, if you note the language for example in Hash overhaul, it says "the order which keys/values will be returned ... will differ from run to run". So it's not like hashes themselves are shuffled in memory, it's the order in which they are iterated over that is randomized. So this always happens at runtime, no matter where the hashes come from. Update: Struck/reworded these sentences as potentially misleading; see BrowserUk's reply below.
Hope this helps,
-- Hauke D
In reply to Re: Curious: are anon-hashes in random order? (updated)
by haukex
in thread Curious: are anon-hashes in random order?
by perl-diddler
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |