2013-08-20 12 views
7

に呼ばれている方法を検出私は、サブルーチンがそのように私はそれがそれぞれのケースに応じて異なる動作を行うことができますと呼ばれているかを検出したいと思います:サブルーチンがPerlの

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

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

が可能ということですか?

答えて

15

使用wantarray

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

もありますします。http:/ /p3rl.org/Wantモジュールですが、この場合は過度のものになる可能性があります。 –

9

はい、あなたが探していることは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(); 

このコードは次のような出力生成:

Called and assigned to an array! 
Called and assigned to a scalar! 
Called in void context! 
関連する問題