in reply to Using & in function calls

As far as I'm concerned, there are two reasons to not use &:

1. using &subname; without braces does not do what you probably think it does. It passes the current value of @_ to the called sub - and subname() update: or subname; does not.

2. when you're passing arguments, most of the time the you are either using braces and/or the subroutine has already been defined, and in both cases the & is not needed. Also strict will warn you if it gets confused in this case. Basically, not using "&" will save you typing.

The only times I use &subname is when a) I want to create a reference to a named subroutine (which is fairly rare), or b) I want to do goto &subname; (which is an even more rare, but does have its uses in that it's the only way to "fake tailrecursion" in perl - see goto)

Replies are listed 'Best First'.
Re^2: Using & in function calls
by demerphq (Chancellor) on Oct 02, 2007 at 08:30 UTC

    ... or b) I want to do goto &subname; (which is an even more rare, but does have its uses in that it's the only way to "fake tailrecursion" in perl - see goto)

    Actually thats not correct, it is neither the only nor the best way to "fake tailrecursion". The best way to fake tail recursion is to use a while or for loop. The overhead of goto &sub is actually quite expensive compared to a proper loop.

    Tail recursion optimisation is only really important in languages which lack looping constructs. Yet the meme that "tail recursion optimisation is cool and useful" somehow manages to leak out of languages that really do need it into languages that don't really need it. And Perl has a rich set of looping constructs making tail recursion and its optimisation much less important than people think. This is actually one of the reasons that perl doesnt bother with this optimisation. (Its not the only reason tho given Perls dynamic nature.)

    Remember that all tail recursion optimisation does is quietly convert your tail recursive call into a loop.

    ---
    $world=~s/war/peace/g

      Well, yes.

      But, it can be useful to have the called subroutine determine the next call instead of moving the determining code to the calling routine. And doing that "naively" will lead you running out of call stack if you have enough nested calls.

      I've used the goto &subroutine; construct to get out of that situation.

      I acknowledge that this isn't strictly tail recursion.