Define how a routine is called in Perl

I would like to know what the subprogram 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 not, do something else: my_subroutine(); 

Is it possible?

+7
function subroutine perl
source share
2 answers

Use wantarray

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

Yes, you are looking for wantarray :

 use strict; use warnings; sub foo{ if(not defined wantarray){ print "Called in void context!\n"; } elsif(wantarray){ print "Called and assigned to an array!\n"; } else{ print "Called and assigned to a scalar!\n"; } } my @a = foo(); my $b = foo(); foo(); 

This code produces the following output:

 Called and assigned to an array! Called and assigned to a scalar! Called in void context! 
+9
source share

All Articles