linux - Perl 中的“If” 'else' 语句

标签 linux perl if-statement sed

我编写了生成一组单词的代码

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/

相关文章:

linux - 在unix下执行有管道的命令会使用多少个进程?

macos - 我该如何修复此 PDL 安装?

perl - 无法在 search.pl 第 10 行的未定义值上调用方法 "headers"

javascript - 如果 else 没有按预期工作,我的逻辑有问题吗?

linux - 使用 sdparm 获取硬盘状态信息

python - Linux 阻塞信号到 Python init

perl - 用空格替换回车,用分号替换逗号?

r - 对列中的多个值使用ifelse语句

java - 在 IF 语句中定义变量 (Java)

linux - 如何更新不同命名空间中现有进程的挂载点