检测Perl中如何调用子例程

时间:2013-08-20 14:10:38

标签: perl function subroutine

我想检测子程序是如何被调用的,所以我可以根据每种情况使其行为不同:

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

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

这可能吗?

3 个答案:

答案 0 :(得分:15)

使用wantarray

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

答案 1 :(得分: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!

答案 2 :(得分:1)

Robin Houston 开发了一个名为 Want 的强大且非常有用的 XS 模块。它扩展了 perl 核心函数 wantarray() 提供的功能,并使您能够确定您的方法是否在对象上下文中被调用。

$object->do_something->some_more;

do_something 中,您可以在返回之前写入:

if( want('OBJECT') )
{
    return( $object );
}
else
{
    return; # return undef();
}