- Perl ›
- builtin functions ›
- here
wantarray function - return scalar or list depending on context
Perl has the concept of context, so you can either scalar or list depending on the context. You can return it.
sub func_name { # process ... return wantarray? List: Scalar; }
You can use wantarray to return the return value by distinguishing between the list context and the scalar context.
The builtin functions that wantarray uses are localtime function.
Don't use the wantarray function
We do not recommend using the wantarray function as it tends to create very hard-to-find bugs. For example, if you think that a scalar will be returned and specify it as an argument of a function, it is possible that a list is returned.
# I expected scala to come back, but in reality the list comes back func (localtime());
To avoid such a bug, don't use the wantarray function and return a scalar variable or a list. ..
Example
This is an example of wantarray.
use strict; use warnings; # Return scalar or list depending on context # wantarray? return list: return scalar print "1: Return scalar or list depending on context\n"; my @nums = (1, 2, 3, 4, 5); my @odd_nums = grep_odd_nums (@nums); my $odd_nums_cnt = grep_odd_nums (@nums); print "In 1-5, the odd numbers are", join(',', @odd_nums). ".\n"; print "The odd number is $odd_nums_cnt.\n\n"; # Subroutine that returns an odd list sub grep_odd_nums { my @nums = @_; my @odd_nums; for my $num (@nums) { if ($num % 2 == 1) { push @odd_nums, $num; } } # If in list context, return @odd_nums # If in scalar context, return the number of @odd_nums return wantarray? @odd_nums: scalar @odd_nums; }