2013-08-20 13 views
7

vorrei rilevare come una subroutine viene chiamata in modo da poter rendere comportarsi in modo diverso a seconda dei casi:Rileva come una subroutine viene chiamata in Perl

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

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

è possibile?

risposta

15

Usa wantarray

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

C'è anche http://p3rl.org/Want module, ma in questo caso potrebbe essere eccessivo. –

9

Sì, quello che stai cercando è 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(); 

Questo codice produce il seguente output:

Called and assigned to an array! 
Called and assigned to a scalar! 
Called in void context!