in reply to Re: Behavior of compile-time constants?
in thread Behavior of compile-time constants?

Don't use the constant pragma
what? personally, i dislike use constant, so i don't use it. but there is no reason not to use it in this case. as Abagail-II stated above, fix the context and the problem is gone.

here's an example (my formatting)

use constant ROTATE => 1; use constant HOLD => 2; use constant FLASH => 3; use constant NUM_MODES => 3; # etc. my %modestring = ( +ROTATE => "a", +HOLD => "b", +FLASH => "c", # etc... );
since i mentioned my dislike of the constant module (pragma?), i'll describe my solution:

sub ROTATE () { 1 } # etc. my %modestring = ( +ROTATE => a, # etc. );

~Particle *accelerates*

Replies are listed 'Best First'.
Re: Behavior of compile-time constants?
by Abigail-II (Bishop) on Jun 14, 2002 at 18:13 UTC
    Since all use constant does is creating such subs, I wonder why you dislike the constant module.

    Abigail, author of the variable pragma.

      i dislike the syntax... i don't think => looks like assignment. also, it creates a sub with an empty prototype behind the scenes, so why introduce the overhead for a syntax i don't agree with? i don't see what it gets me.

      the use of subroutines with empty prototypes as inlinable is well documented in perlsub, and i expect anyone maintaining my code is familiar with this doc.

      ~Particle *accelerates*

        I wouldn't worry about the overhead of 70 lines of code and one function call per constant, unless you're writing a very very small program. If the manpage syntax is really a problem, why not use a skinny comma?
        use constant 'FOO', 2;
Re: Re: Re: Behavior of compile-time constants?
by perrin (Chancellor) on Jun 14, 2002 at 18:15 UTC
    That's just it: you shouldn't have to fix the context. Knowing you have to fix the context means knowing how the constant pragma is implemented, and that's not something you should need to know.
      No, all you need to know is how => works. You have the same problem in:
      #!/usr/bin/perl use strict; use warnings 'all'; sub foo { my %hash = (shift => 1); print keys %hash, "\n"; } foo "bar"; __END__
      That prints shift and not bar.

      Abigail

        My recommendation to him was to use variables for his constants. (Yes, I know that sentence sounds bizarre.) Variables certainly behave differently in different contexts, but people are not as likely to make mistakes with them because they know they've got a variable rather than some mysterious constant thing.