DavidSzczesniak
12/14/2017 - 5:46 PM

Context Awareness - wantarray()

This allows you to determine whether you've invoked a function in void, scalar or list context. The wantarray built-in returns 'undef' for void context, a false value for scalar context, and a true value for list context.

sub context_sensitive {
  my $context = wantarray();
  return qw(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();