Perl:如何检查子例程返回的内容

发布于 2024-11-18 13:31:00 字数 210 浏览 7 评论 0原文

我有一个子例程,当一切顺利时,它将返回两个哈希值。但是子检查命令的输出,如果它匹配某个模式,它将返回“-1”。无论如何,有没有办法从我调用它的地方检查子例程的返回?

有点像:

if (RETURN_VALUE == -1){
   do something}
   else
   go as normal with the hashes

I have a subroutine that will return two hashes when all goes well. But the sub checkouts output of command and if it matches a certain pattern, it returns with "-1". Is there anyway to check the return of the subroutine from where I called it?

Kinda like:

if (RETURN_VALUE == -1){
   do something}
   else
   go as normal with the hashes

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情魔剑神 2024-11-25 13:31:00

一个函数如何返回两个哈希值

如果您指的是 hashrefs,那么检查将非常简单:

my ($h1,$h2) = myFunction();
if ( !ref($h1) || (ref($h1) ne "HASH"))
{
   die 'error';
}

How could one function return two hashes?

If you mean hashrefs, the check would be quite simple:

my ($h1,$h2) = myFunction();
if ( !ref($h1) || (ref($h1) ne "HASH"))
{
   die 'error';
}
快乐很简单 2024-11-25 13:31:00

您的函数应该在成功时返回对两个哈希值的引用,在失败时不返回任何内容。然后你可以检查函数调用的真值。

sub myfunc {
    my %hash1;
    my %hash2;
    return (\%hash1, \%hash2);
}

my $ref1;
my $ref2;
unless (($ref1, $ref2) = myfunc()) { 
    print "Something went wrong\n";
} else { 
    print "OK\n";
}

You function should return references to the two hashes on success and nothing upon failure. Then you can just check the truth value of the function call.

sub myfunc {
    my %hash1;
    my %hash2;
    return (\%hash1, \%hash2);
}

my $ref1;
my $ref2;
unless (($ref1, $ref2) = myfunc()) { 
    print "Something went wrong\n";
} else { 
    print "OK\n";
}
笑叹一世浮沉 2024-11-25 13:31:00

如果您从子例程返回两个(或任何数字)散列,则结果将是单个散列。您将无法以正常方式将原始哈希值与结果分开。返回哈希引用不会出现此问题。

假设 foo() 在模式匹配时返回两个哈希引用,在不匹配时返回 -1。

my ( $value_1, $value_2 ) = foo;

if ( $value_1 == -1 ) {
    # pattern did not match
}
else {  # for strict checks: elsif ( ref $value_1 eq 'HASH' && ref $value_2 eq 'HASH' ) {
    # pattern matched
}

If you return two (or any number for that matter) hashes from a subroutine, the result will be a single hash. You will not be able to separate the original hashes from the result in a normal manner. Returning hash references will not exhibit this problem.

Suppose foo() returns two hash references when the pattern is matched and returns -1 when it does not match.

my ( $value_1, $value_2 ) = foo;

if ( $value_1 == -1 ) {
    # pattern did not match
}
else {  # for strict checks: elsif ( ref $value_1 eq 'HASH' && ref $value_2 eq 'HASH' ) {
    # pattern matched
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文