How to check if any of the value returned is 1 in Perl

Viewed 125

I'm using Perl in Windows and I have written the code in Perl for calling 2 jar files and i want to check if the value returned by any of these 2 jar files is 1.How can i implement this in Perl Code written to call the 2 jars(Sample1 and Sample2) in Perl

        my $cmd = "";
        my $res = "";
        my $cmd1 = "";
        my $res1 = "";
        $cmd = "java -jar C:/xampp/perl/bin/Sample1.jar";
        $res = qx/$cmd/;
        print "$res\n";

        $cmd1 = "java -jar C:/xampp/perl/bin/Sample2.jar";
        $res1 = qx/$cmd1/;
        print "$res1\n";

I want to check if any of these two jar files i.e If either of Sample1.jar or Sample2.jar has returned value 1.I'm using return statement in these jar files to return the value but I'm not able to take those values in perl and check if the value returned is 0 or 1 .Can anyone tell me what modifications should be made so that it would work properly.I tried using

if($res==1 || $res1==1)
{
$val =1;
print $val;
}
else
{
$val=0;
print $val;
}

But this didn't work.It's giving me an error Argument "" isn't numeric in numeric eq (==) at Sample1.pl line 30, line 4. Argument "" isn't numeric in numeric eq (==) at Sample2.pl line 34, line 4.

3 Answers

$res apparently contains an empty string, so you are effectively doing

"" == 1

This is a numeric comparison, but the empty string isn't a number. You could use a string comparison

$res eq "1"

or you could handle the empty string specially

length($res) && $res == 1

To avoid this warning, you can use the function looks_like_number provided by the package Scalar::Util

use Scalar::Util qw(looks_like_number); 
if((looks_like_number($res) && $res==1) || (looks_like_number($res1) && $res1==1))
{
 ..

Try this to get the values:

$cmd = "java -jar C:/xampp/perl/bin/Sample1.jar";
$response = `$cmd`

if ($response eq 1){...}

See documentation

Or did you want to get the return code?

See documentation

Snippet of this doc:

    my @args = ("command", "arg1", "arg2");
    system(@args) == 0
        or die "system @args failed: $?";

    if ($? == -1) {
        print "failed to execute: $!\n";
    }
    elsif ($? & 127) {
        printf "child died with signal %d, %s coredump\n",
            ($? & 127),  ($? & 128) ? 'with' : 'without';
    }
    else {
        printf "child exited with value %d\n", $? >> 8;
    }

Related