7

我想检测一个子程序是如何被调用的,所以我可以根据每种情况让它表现不同:

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

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

那可能吗?

4

3 回答 3

17

使用需要数组

if(not defined wantarray) {
    # void context: foo()
}
elsif(not wantarray) {
    # scalar context: $x = foo()
}
else {
    # list context: @x = foo()
}
于 2013-08-20T14:14:52.580 回答
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!
于 2013-08-20T14:15:36.917 回答
1

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

$object->do_something->some_more;

在这里do_something你可以在返回之前写:

if( want('OBJECT') )
{
    return( $object );
}
else
{
    return; # return undef();
}
于 2021-05-14T06:05:33.680 回答