简体   繁体   English

Perl 中的“If”“else”语句

[英]'If' 'else' statement in Perl

I have written code which yield a group of words我写了产生一组单词的代码

my $uptime = `command | sed -n "xp" | cut -d" " -fx`;

The above command gives me the below word.上面的命令给了我下面的词。

not running

I would like to use this word in an if statement like below:我想在如下if语句中使用这个词:

if ($uptime = $not){
    $run = `command`;
    $start = `start`;

I have declared a variable $not and put "not running" in it.我已经声明了一个变量$not并在其中放置了"not running" Though the script is working, it is doing the opposite, when the program is running.尽管脚本正在运行,但在程序运行时却相反。 The below command gives a different word which (like "ok") is not in the variable $not , but the script is restarting the program.下面的命令给出了一个不同的词(如“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)'

are two different things.是两个不同的东西。 eq is string comparison operator so it will return 1 when the comparison is equal and '' when the condition does not satisfy, whereas if ($uptime = $not) will return true when $not evaluates to true because you are assigning one variable to another using assignment operator = . eq是字符串比较运算符,因此当比较相等时它将返回 1,当条件不满足时返回'' ,而if ($uptime = $not)将在$not评估为真时返回真,因为您将一个变量分配给另一个使用赋值运算符= So please change your code.所以请更改您的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM