in reply to subroutine constants

The best way is
use constant BUFFER => 2048;

                - Ant
                - Some of my best work - Fish Dinner

Replies are listed 'Best First'.
Re: Re: subroutine constants
by Anonymous Monk on Sep 21, 2001 at 00:36 UTC
    perhaps I was unclear.....?
    I know of the various other methods of creating constants. I would just like to know the difference between the two used above as they both compile the same in my script.
    #!/usr/bin/perl -w use strict; sub BUFFER { 2048 } print BUFFER, "\n";
    and
    #!/usr/bin/perl -w use strict; sub BUFFER () { 2048 } print BUFFER, "\n";
      I don't know that there is much real difference other than one will fail if you try to pass it arguments and one won't (I think)... in general though, I believe use Constants is better since it does some behind the scenes work and is done compile time... if you are going to do it the hard way, probably sub BUFFER () { 2048 } is the better way to go.

                      - Ant
                      - Some of my best work - Fish Dinner

        Ah, but: sub BUFFER() { 2048 } is also a compile-time construct.

        The () means that uses of BUFFER can be optimized away so that the code gets compiled as if you said 2048 directly. Without the (), each time an instance of BUFFER is encountered at run time, a Perl subroutine call has to be executed.

        I doubt you'd be able to notice a speed difference between the two without trying really hard. But it also makes the compiled code a little smaller and declares your intention to not change this definition at run time.

                - tye (but my friends call me "Tye")
      sub BUFFER () { 2048 }
      implements prototyping, perl's somewhat limited way of compile-time subroutine arg checking.

      Doing this like shown above (the empty prototype) indicates that the sub takes no args, and if you try to pass it any args, it will produce a compile time error.

      I am also somewhat sure that the difference in your compilation would be very subtle, if much different at all.

      These as far as I know are considered inline subroutine constants.