Advanced Functions
Explore advanced Perl functions by understanding context awareness, recursion techniques, and lexical variable scopes. Learn to write efficient recursive functions and apply tailcall optimization for better performance and memory management.
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.
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 ...