in reply to Behavior of compile-time constants?

Don't use the constant pragma. It will 'constant'ly trip you up with problems like this. Use ordinary variables in all caps instead.

The reason your code is breaking is that '=>' stringifies the left argument. The constants are actually implemented as subroutines, and they are not being called. You can fix this by saying "ROTATE() =>" instead of "ROTATE =>", but why bother? Just use variables.

  • Comment on Re: Behavior of compile-time constants?

Replies are listed 'Best First'.
Re: Re: Behavior of compile-time constants?
by particle (Vicar) on Jun 14, 2002 at 18:09 UTC
    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*

      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*

      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