in reply to Re: subroutine constants
in thread subroutine constants

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";

Replies are listed 'Best First'.
Re: Re: Re: subroutine constants
by John M. Dlugosz (Monsignor) on Sep 21, 2001 at 00:40 UTC
Re: Re: Re: subroutine constants
by suaveant (Parson) on Sep 21, 2001 at 00:41 UTC
    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")
        Ooooh... ahhhh... teach me oh great one ;)

        I suppose if you had a few thousand constants you would notice it... :)

                        - Ant
                        - Some of my best work - Fish Dinner

Re: Re: Re: subroutine constants
by czarfred (Beadle) on Sep 21, 2001 at 03:47 UTC
    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.