检测Perl中如何调用子例程

cal*_*llo 7 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();
Run Code Online (Sandbox Code Playgroud)

那可能吗?

AKH*_*and 15

使用wantarray

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


小智 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();
Run Code Online (Sandbox Code Playgroud)

此代码生成以下输出:

Called and assigned to an array!
Called and assigned to a scalar!
Called in void context!
Run Code Online (Sandbox Code Playgroud)