简体   繁体   中英

'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 ($uptime = $not){
    $run = `command`;
    $start = `start`;

I have declared a variable $not and put "not running" in it. 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.

#!/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 = . So please change your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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