gpt4 book ai didi

Perl,如何创建类似子程序的 map/grep?

转载 作者:行者123 更新时间:2023-12-05 01:01:26 26 4
gpt4 key购买 nike

我想创建一个像 grep {} @ 这样的子程序或 map {} @可以处理代码和/或 bool 输入。不知何故,互联网上没有太多关于这方面的信息。

我试图在下面创建子,但它甚至无法处理第一个测试。我收到错误 Can't locate object method "BoolTest" via package "input" (perhaps you forgot to load "input"?) at C:\path\to\file.pl line 16. .

这怎么会认为它是一个对象?我没有正确创建 BoolTest 吗?

# Example senarios
BoolTest { 'input' =~ /test[ ]string/xi };
BoolTest { $_ =~ /test[ ]string/xi } @array;
BoolTest(TRUE);

# Example subroutine
sub BoolTest
{
if ( ref($_[0]) == 'CODE') {
my $code = \&{shift @_}; # ensure we have something like CODE
if ($code->()) { say 'TRUE'; } else { say 'FALSE'; }
} else {
if ($_[0]) { say 'TRUE'; } else { say 'FALSE'; }
}
}

最佳答案

要传递代码引用,您可以使用以下内容:

sub BoolTest { ... }

BoolTest sub { 'input' =~ /test[ ]string/xi };
BoolTest sub { $_ =~ /test[ ]string/xi }, @array;
BoolTest(TRUE);

您可以让 sub 具有与 map BLOCK LIST 类似的语法。 , 通过使用 &@原型(prototype)。
sub BoolTest(&@) { ... }

BoolTest { 'input' =~ /test[ ]string/xi };
BoolTest { $_ =~ /test[ ]string/xi } @array;

这会创建相同的匿名子,所以 return , last , 等将与第一个片段中的行为相同。

请注意,原型(prototype)版本不接受
BoolTest(TRUE);

除非你覆盖原型(prototype)
&BoolTest(TRUE);

但是你不应该期望你的调用者这样做。根据您的示例,您可以让他们使用以下内容,但第二个子可能会更好。
BoolTest { TRUE };

关于Perl,如何创建类似子程序的 map/grep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com