dReKurCe has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks I have an inquiry with regards to the wantarray function.Specifically, I would like to know if my understanding of it's use could be ellucidated with some code examples. The wantarray seems to be useful when a subroutine processes a list in which the first value is of some significance. How could a function be designed to take advantage of wantarray in either of the conditions of its relevance to lists passed into the subroutine or lists returned?
  • Comment on List Processing Functions and Wantarray

Replies are listed 'Best First'.
Re: List Processing Functions and Wantarray
by davido (Cardinal) on Feb 05, 2005 at 16:23 UTC

    An example:

    my @people = qw/jerry kramer george elaine/; sub sortnames { my( @names ) = @_; @names = sort @names; return wantarray ? @names : join ' ', @names; } my $sorted_string = sortnames( @people ); my @sorted_list = sortnames( @people ); print $sorted_string, "\n"; print "$_\n" foreach @sorted_list;

    The idea is that if the function is evaluated in list context, it returns one thing, and if evaluated in scalar context, it returns something else. In this case, you either get a sorted list of names, or you get a single string containing the sorted names. Another classic example of "wantarray" type functionality at work is the built-in localtime function, where in list context you get a list containing year, day, month, and so on, while in scalar context you get a stringified time/date stamp. I hope this helps...


    Dave

      Dave,
      ...if the function is evaluated in list context, it returns one thing, and if evaluated in scalar context, it returns something else.

      True in list context, false in scalar context, and undef in void context. It is important to note that you need to test for definedness prior to truth if all 3 contexts are important to you because undef will give a false positive. See perldoc -f wantarray and also Want which is pretty scary code.

      Cheers - L~R

Re: List Processing Functions and Wantarray
by Tanktalus (Canon) on Feb 05, 2005 at 16:27 UTC

    Perhaps you could start with some guesses?

    sub localtime { my $time = shift || time; # code to convert to @time_parts if (wantarray) { return @time_parts; } elsif (defined wantarray) { return sprintf("...",@time_parts); } }

    In this example, localtime is aware of whether you want an array (in which case it returns all the pieces so you can do what you want with it), or you want a scalar (in which case it prints it in human-readable format to a string, and returns that), or you don't want anything (wantarray returns undef - so it doesn't return anything).