【问题标题】:'If' 'else' statement in PerlPerl 中的“If”“else”语句
【发布时间】:2013-11-02 05:07:42
【问题描述】:

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

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`;
}

【问题讨论】:

  • = 运算符是一个赋值运算符。您的条件是将$uptime 设置为等于$not。我确定这不是你想要的。在 Perl 中,当您想要比较两个字符串是否相等时,您可以使用 eq 运算符:if( $uptime eq $not ) { ...
  • 我试图做的是下面的行给出一个结果“未运行”> $uptime = command | sed -n "xp" | cut -d" " -fx;当不运行发生时,我想执行 if 语句中的内容。我认为比较两个字符串可以让我执行 if 语句。但是,当我使用 >if( $uptime eq $not ) 时,脚本不起作用。

标签: linux perl if-statement sed


【解决方案1】:
'if ($uptime = $not)' and 'if ($uptime eq $not)'

是两个不同的东西。eq是字符串比较运算符,所以当比较相等时它会返回1,当条件不满足时''会返回,而if ($uptime = $not)会在$not计算结果为真时返回真因为您正在使用赋值运算符= 将一个变量分配给另一个变量。所以请更改您的代码。

your condition will look like the following .
$uptime=chomp($uptime);
if ($uptime eq $not){
//your code
}

【讨论】:

  • 你想要的输出是什么@TahnanALAnas?
  • 当我没有从 $uptime 命令运行时,我想执行 if 语句中的内容,如果 $uptime 给出的东西比脚本什么都不做。
  • 如果允许提供完整的脚本并提供任何帮助,我会将我写的内容放在这里。
  • 你更新你正在使用的代码。但我认为我在回答中提到的代码会做你想要的。
  • 并检查 $uptime 的值。确保它不包含 \n 或任何特殊字符。我猜这可能是您的条件失败的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2014-03-30
  • 2015-10-28
  • 2017-02-05
  • 1970-01-01
  • 2015-07-06
  • 2012-08-05
相关资源
最近更新 更多