in reply to List Processing Functions and Wantarray

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

Replies are listed 'Best First'.
Re^2: List Processing Functions and Wantarray
by Limbic~Region (Chancellor) on Feb 05, 2005 at 17:02 UTC
    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