Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

Several standard perl functions return different values depending of the context these functions are called.

For example, localtime() returns a string of the form "Wed Nov 15 11:10:36 2006" when called in a scalar context; in a list context it returns a 9-element like this: (10 46 11 15 10 106 3 318 1).

To implement the same behaviour in custom made subroutines, use the function wantarray().

wantarray() returns true if the context of the currently executing subroutine is a list context, returns false in a scalar context and returns undefined in a void context.

Example:

sub example_routine
{
  $return_value = "This is a test";
 
  #-- undefined context
  return if ( ! defined wantarray );
  #-- list context
   return split $return_value if ( wantarray );
  #-- neither undefined nor list context, return scalar
  return $return_value;
}