Search code examples
perlsubroutine

Detect how a subroutine is called in Perl


I would like to detect how a subroutine is called so I can make it behave differently depending on each case:

# If it is equaled to a variable, do something:
$var = my_subroutine();

# But if it's not, do something else:
my_subroutine();

Is that possible?


Solution

  • Use wantarray

    if(not defined wantarray) {
        # void context: foo()
    }
    elsif(not wantarray) {
        # scalar context: $x = foo()
    }
    else {
        # list context: @x = foo()
    }