wantarray is yet another reason why perl is a great programming language. You can use wantarray to have change what your function returns based upon the context in which it was called.

For example, say you have a function called unique() which takes an @array as its argument. You can use wantarray to have unique() return a list of unique elements from @array or the number of unique elements depending upon context.

sub unique {
  my @array = @_;

  my %temp = map { $_ => 1 } @array;

  if ( wantarray() ) {
    return sort( keys( %temp ) );         # the unique elements
  }
  else {
    return scalar( keys( %temp ) );    # the number of unique elements
  }
}

You can now call unique() as follows:

  my @unique_array = unique( @array );      # get a sorted unique list

  my $unique_number = unique( @array );    # get the number of elements.

Log in or register to write something here or to contact authors.