我编写了生成一组单词的代码
my $uptime = `command | sed -n "xp" | cut -d" " -fx`;
上面的命令给了我下面的单词。
not running
我想在 if 语句中使用这个词,如下所示:
if ($uptime = $not){
$run = `command`;
$start = `start`;
我声明了一个变量$not
并将“not running”
放入其中。尽管脚本正在工作,但当程序运行时,它却在做相反的事情。下面的命令给出了一个不同的单词(如“ok”),它不在变量 $not
中,但脚本正在重新启动程序。
#!/usr/bin/perl
use warnings;
use strict;
$not = "not running";
$uptime = `command | sed -n "xp" | cut -d" " -fx`;
if ($uptime = $not){
# If not running, the program then executes the below, else do nothing
$run = `cp /home/x`;
$start = `start`;
}
最佳答案
'if ($uptime = $not)' and 'if ($uptime eq $not)'
是两个不同的东西。eq
是字符串比较运算符,因此当比较相等时它将返回 1,当条件不满足时它将返回 ''
,而当 $not
计算结果为 true 时,if ($uptime = $not)
将返回 true,因为您使用赋值运算符 =
将一个变量分配给另一个变量。所以请更改您的代码。
your condition will look like the following .
$uptime=chomp($uptime);
if ($uptime eq $not){
//your code
}
关于linux - Perl 中的“If” 'else' 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19739151/