使用标量作为perl中的条件 [英] Using a scalar as a condition in perl

查看:115
本文介绍了使用标量作为perl中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个计时器......所以,如果有任何我在提出问题时没有注意的话,请告诉我。

First timer...so let me know if there is anything that I have not paid attention to whilst posing a question.

问题是如何使用标量作为条件,因为下面的代码不起作用。

The question is how to use a scalar as a condition, as the code below does not work.

my @parameter=('hub');

my %condition;
$condition{'hub'}{'1'}='$degree>=5';

foreach (@parameter) {
       if ($condition{$_}{'1'}) {..}
}

我认为这是因为条件没有被正确解释,所以我也尝试了以下,但也没有用。

I thought that is because the condition is not interpreted correctly, so I also tried the following, which also did not work.

if ("$condition{$parameter}{'1'}") { ..}

非常感谢任何帮助。 :)

Would really appreciate any help. :)

推荐答案

您要么需要字符串eval,它将字符串计算为Perl代码

You either want string eval, which evaluates a string as Perl code

if (eval $condition{$_}{'1'}) { ...

或者更安全的方法是使用代码参考

or perhaps a more secure approach would be using code references

$condition{'hub'}{'1'} = sub { return $degree>=5 };

if ($condition{$_}{'1'}->()) { ...

在第二个示例中,您将一段代码附加到变量。 $ var->()语法执行代码并计算代码的返回值。

In the second example, you are attaching a piece of code to a variable. The $var->() syntax executes the code and evaluates to the return value of the code.

这篇关于使用标量作为perl中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆