【问题标题】:Can I call a Perl OO function without first saving the object to a variable?我可以在不先将对象保存到变量的情况下调用 Perl OO 函数吗?
【发布时间】:2025-12-01 20:05:02
【问题描述】:

如何将这两个语句 sn-p 变成一个语句?

my $handle = &get_handle('parameter');
$handle->do_stuff;

类似于{&get_handle('parameter')}->do_stuff;,但正确的语法是什么?

【问题讨论】:

  • 一般来说,你不应该在函数调用前加上&。在您的示例中,这样做会更好my $handle = get_handle('parameter')

标签: perl oop function methods handle


【解决方案1】:

不需要在-> 的左侧使用变量。它可以是任何表达式,所以你可以简单地使用

get_handle('parameter')->do_stuff

其实很常见。例如,

$self->log->warn("foo");          # "log" returns the Log object.
$self->response->redirect($url);  # "response" returns a Response object.
$self->config->{setting};         # "config"s return a hash.

【讨论】:

  • +1 注意,这只有在方法返回一个对象时才有效。在示例中,如果get_handle('parameter') 只作用于对象但返回undef 或对象以外的其他内容,则调用->do_stuff 将导致运行时错误。
  • 这就是为什么如果我们想要这种接口,我们应该使用 null 对象代替 undef 作为返回值。 ;)
  • @Joel,如果get_handle 返回undef,他的原件也不会起作用。
  • @ikegami,碰巧我的get_handledie 早于返回undef。 :)
【解决方案2】:
get_handle('parameter')->do_stuff

相关:When should I use the & to call a Perl subroutine?

【讨论】:

    最近更新 更多