perl function wantarray

http‮‬s://www.theitroad.com

In Perl, the wantarray function is used to determine whether a function or subroutine is called in a list context or a scalar context. The function returns a boolean value indicating the calling context.

Here is an example:

sub get_array_or_scalar {
    if(wantarray) {
        return (1, 2, 3);   # return an array
    }
    else {
        return "scalar";    # return a scalar
    }
}

my $scalar_value = get_array_or_scalar();
print "Scalar context: $scalar_value\n";  # prints "Scalar context: scalar"

my @array_value = get_array_or_scalar();
print "Array context: @array_value\n";   # prints "Array context: 1 2 3"

In this example, we define a subroutine get_array_or_scalar which checks whether it is called in an array context or a scalar context using the wantarray function. If the function is called in a list context, it returns an array (1, 2, 3); otherwise, it returns a string "scalar".

We then call the get_array_or_scalar subroutine in both array context and scalar context and print out the results. In scalar context, we store the return value of the function in a scalar variable $scalar_value and print it out. In array context, we store the return value of the function in an array variable @array_value and print it out.