Perl | wantarray() Function

wantarray() function in Perl returns True if the currently executing subroutine expects to return a list value, and false if it is looking for a scalar value.

Syntax: wantarray()

Returns: true for list value and false for scalar values

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Subroutine to call wantarray() function
sub geeks
{
    return(wantarray() ? ("Geeks", "For", "Geeks") : 1);
}
  
# Calling the subroutine 
# in scalar and array context
$value = geeks();
@value = geeks();
  
# Printing the values in both contexts
print("Value in Scalar context: $value\n");
print("Value in List Context: @value");

chevron_right


Output:

Value in Scalar context: 1
Value in List Context: Geeks For Geeks

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Subroutine to call wantarray() function
sub geeks
{
    if(wantarray())
    {
        # Addition of two numbers when 
        # wantarray() function is called
        # in list context
        $c = $a + $b
    }
    else
    {
        # When wantarray() is called 
        # in Scalar context
        return 1;
    }
}
  
# Driver Code
$a = 10; $b = 20; $c = 0;
  
# Calling Subroutine in scalar and list contexts
$value = geeks($a, $b);
@value = geeks($a, $b);
  
# Printing values in both the contexts
print("Value when called in Scalar context: $value\n");
print("Value when called in List Context: @value");

chevron_right


Output:

Value when called in Scalar context: 1
Value when called in List Context: 30


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.