1

如何使用 Perl 函数返回布尔值和字符串?

例如,我正在使用正则表达式在字符串中查找内容。如果找到,则返回 true 并将值赋给 $msg,否则返回 false 并将另一个值赋给 $msg。

现在我想通过“return ($result, $msg); ”返回 $result (boolean) 和 $msg (String),并且它已经过验证。我想知道这样做是否很好,或者有更好的方法吗?我不想让其他人在查看我的代码时感到困惑。

use constant { true => 1, false => 0 };
my $output = "hello world";
my $msg;
my $result;

sub is_string_found
{
    if ($output =~ /hello/;)
    {
        $msg = "string is found";
        $result = true;
    }
    else
    {
        $msg = "string is not found";
        $result = false;
    }

    return ($result, $msg);
}
4

2 回答 2

3

除了使用常量true和之外,您的代码还有一些问题false

  • 你在你的函数之外声明$msg和。$result最好减少这些变量对函数的可见性。实际上,您甚至不需要它们。

  • 您通过外部范围内的变量将参数传递给您的 sub,并以相同的方式返回值。改用子例程参数和返回值。

  • 你有一个错误;的条件if

您的子可以缩短为

sub is_string_found {
  my ($str) = @_;
  return 1, "string is found" if $str =~ /hello/;
  return 0, "string is not found";
}

然后可以像这样使用它

my ($ok, $message) = is_string_found("hello world");

这是最好的,也是最明显的解决方案(对于 Perl 程序员)。


您还可以使用外参数,以便只返回成功值:

sub is_string_found ($\$) {
  my ($str, $out_ref) = @_;
  if ($str =~ /hello/) {
    $$out_ref = "string is found";
    return 1;
  } else {
    $$out_ref = "string is not found";
    return;
  }
}

return没有值undef在标量上下文中返回,列表上下文中的空列表。然后可以像这样调用它

my $ok = is_string_found "hello world", my $message;

或者

my $message;
is_string_found "hello world", $message
  or log_warning $message;

注意:你必须在第一次使用它之前声明它,要么在使用前定义它,要么将语句放在sub is_string_found ($\$);脚本顶部附近。

您不必使用原型(可以改为使用 的别名行为@_),但我并不特别喜欢该解决方案

于 2013-05-28T00:33:58.447 回答
2

您在返回列表方面所做的一切都很好。但是使用哈希可能会更好:

sub is_string_found {
    my %h; 
    if ($output =~ /hello/)
    {   
        %h = (msg=>"string is found", retval=>1);
    }
    else
    {   
        %h = (msg=>"string is not found", retval=>0);
    }
    return %h; 
}

%d = is_string_found();
print $d{msg}, "\n" if not $d{retval};
于 2013-05-28T00:28:36.690 回答