Advanced Functions
Learn about advanced functions in Perl.
We'll cover the following...
Functions are the foundation of many advanced Perl features.
Context awareness
Perl’s built-ins know whether we’ve invoked them in void, scalar, or list context. So too can our functions. The wantarray
built-in returns undef
to signify void context, a false value to signify scalar context, and a true value to signify list context. Yes, it’s misnamed; see perldoc -f wantarray
for proof.
sub context_sensitive {my $context = wantarray();return 'List context' if $context;say 'Void context' unless defined $context;return 'Scalar context' unless $context;}context_sensitive();say my $scalar = context_sensitive();say context_sensitive();
This can be useful for functions that might produce expensive return values
to avoid doing so in void context. Some idiomatic functions return a list-in-list context and the first element of the list or an array reference in scalar
context. However, there is no single best recommendation for the use of
wantarray
. Sometimes, it’s clearer to write separate and unambiguous functions,
such as get_all_toppings()
and get_next_topping()
.
Robin Houston’s Want
and Damian Conway’s ...