in reply to Re: Label makes a sub to return empty list -- "secret"? documented?
in thread Label makes a sub to return empty list -- "secret"? documented?

to make this clearer for beginners: I wouldn't call the effects undocumented, just an idiomatic approach (and micro optimization)

FWIW using a label can have unwanted global side-effects, because a nested sub could have a goto _;

some experiments:

$ perl -MO=Concise,ret,empty,label -e'sub ret {return}; sub empty {()} +; sub label {LABLE:};' main::ret: 4 <1> leavesub[1 ref] K/REFC,1 ->(end) - <@> lineseq KP ->4 1 <;> nextstate(main 2 -e:1) v ->2 3 <@> return K ->4 2 <0> pushmark s ->3 main::empty: 7 <1> leavesub[1 ref] K/REFC,1 ->(end) - <@> lineseq KP ->7 5 <;> nextstate(main 4 -e:1) v ->6 6 <0> stub P ->7 main::label: 9 <1> leavesub[1 ref] K/REFC,1 ->(end) 8 <;> nextstate(LABLE: main 6 -e:1) P ->9 -e syntax OK

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

UPDATE

¹) jdporter pointed out: you say "last statement", but you mean "last expression evaluated". Not the same thing!

well yes not every statement is an expression leading to a value, and it's the last in the current code flow which counts (think if/else), not in the sub.

That's what the docs say:

If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while, the returned value is unspecified. The empty sub returns the empty list

Replies are listed 'Best First'.
Re^3: Label makes a sub to return empty list -- "secret"? documented?
by Jenda (Abbot) on Sep 11, 2025 at 17:43 UTC

    I would have expected the empty return to have been optimized away during compilation two decades ago at least.

    Jenda
    1984 was supposed to be a warning,
    not a manual!

      well B::Deparse would fail then ...

      There is also benefit in consistent behavior.

      I'd rather prefer a second version of the sub construct (something like def ) which implements this, instead of relying on such syntax tricks.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

        Fail in what way? In not producing the exact (save for whitespace) copy of the original code? Is that really a problem? Both the compiled and "deparsed" code would still have to denote that the subroutine isn't returning the value of the statement before the empty return.

        Empty return is the only solution that is NOT a syntax trick, therefore it ought to be implemented efficiently and if B::Deparse needs to produce code of a subroutine that returns nothing, the empty return should be the "inferred" solution even if it means that deparsing turns some of those tricks into an explicit empty return.

        Jenda
        1984 was supposed to be a warning,
        not a manual!