in reply to Using Constants in Perl

In PBP, Damian recommends Readonly instead of use constant.

--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Using Constants in Perl
by moklevat (Priest) on Feb 28, 2006 at 16:58 UTC
    Just to elaborate a bit (I happened to read this chapter in PBP yesterday). He recommends Readonly because bareword constants (ala use constant) can't be interpolated. Moreover, Readonly allows lexically scoped variables to be created at runtime, but use constant creates package scoped variables at run time.

      A Better reason that I find for using Readonly is that is makes your code easier to understand. If you do not have Readonly with XS compiled then you take a performance hit but you generally only see that using a Readonly hash.

      Another Advantage Readonly has over use constant is that you can declare a hash, you cannot do that with use constant.

        I was pretty sure you could declare a hash with use constant.. or well, a hash reference anyways:
        use constant HASH_REF => { constant_key => 'constant_value', ... };
        Then use it like you would any hashref ie:
        print HASH_REF->{constant_key}
        or
        foreach my $key (keys %{ &HASH_REF }) { ... }
        or the even weirder:
        foreach my $key (keys %{ HASH_REF() }) { ... }