LanX has asked for the wisdom of the Perl Monks concerning the following question:
We had a confused discussion at last Darmstadt Perlmongers meeting, about how the callers context of a sub effects the context within the sub.
Side question was how to reliably force void-context.
Though the perldocs of return could be clearer, I came up with basic rules I wanna share and discuss here:
1. Only returned statements/lines have the callers context.
2. All other lines are per default in void context.
3. Implicitly returned statements - i.e. final but without return keyword - are like in case 1 also in callers context.
The last point can be sometimes confusing, because with nested control flow it's not always instantly clear where a sub possibly drops out.
Please see the following testcode and output for deeper understanding and as a base for your own tests.
Questions, discussions and modifications are welcome.
# -------------------- # force context # -------------------- sub VOID (&) { print "VOID:\t"; $_[0]->(); return; } sub LIST (&) { print "LIST:\t"; () = $_[0]->(); return; } sub SCALAR (&) { print "SCALAR:\t"; scalar $_[0]->(); return; } # -------------------- # tests # -------------------- sub tst_context { unless (defined wantarray) { print "is void\n"; } elsif (wantarray) { print "is list\n"; } else { print "is scalar\n"; } } SCALAR { tst_context() }; LIST { tst_context() }; VOID { tst_context() }; # -------------------- # implicit_returns # -------------------- sub implicit_returns { print "implicit_returns(@_)\t"; if ($_[0]) { tst_context() # caller's context } else { tst_context() # caller's context } } SCALAR { implicit_returns(1) }; SCALAR { implicit_returns(0) }; LIST { implicit_returns(1) }; LIST { implicit_returns(0) }; VOID { implicit_returns(1) }; VOID { implicit_returns(0) }; # -------------------- # no_implicit_returns # -------------------- sub no_implicit_returns { print "no_implicit_returns(@_)\t"; if ($_[0]) { tst_context() # void context } else { tst_context() # void context } return; # last execution! } SCALAR { no_implicit_returns(1) }; SCALAR { no_implicit_returns(0) }; LIST { no_implicit_returns(1) }; LIST { no_implicit_returns(0) }; VOID { no_implicit_returns(1) }; VOID { no_implicit_returns(0) };
Output:
SCALAR: is scalar LIST: is list VOID: is void SCALAR: implicit_returns(1) is scalar SCALAR: implicit_returns(0) is scalar LIST: implicit_returns(1) is list LIST: implicit_returns(0) is list VOID: implicit_returns(1) is void VOID: implicit_returns(0) is void SCALAR: no_implicit_returns(1) is void SCALAR: no_implicit_returns(0) is void LIST: no_implicit_returns(1) is void LIST: no_implicit_returns(0) is void VOID: no_implicit_returns(1) is void VOID: no_implicit_returns(0) is void
UPDATE: same rules apply to evals:
# -------------------- # eval # -------------------- LIST { eval "print 'eval '; return tst_context(); 'never executed'" }; #-> LIST: eval is list
Cheers Rolf