Mahesh
Mahesh

Reputation: 233

Nested 'if' or something else in Perl

I struck in a simple nested if statement.

The requirement is as below.

if (Condition1) {
    if (Condition2) {
        print "All OK";
    }
    else {
        print "Condition1 is true but condition2 not";
    }
    else {print "Condition1 not true";
}

Is it possible to write this code in Perl or is there another short or better way to fulfil this condition?

Upvotes: 2

Views: 11629

Answers (6)

null
null

Reputation: 928

if (!Condition1) {
  print "Condition1 not true";
}
else {
  if (Condition2) {
    print "All OK";
  }
  else {
    print "Condition1 is true but condition2 not";
  }
}

Upvotes: 0

Zaid
Zaid

Reputation: 37156

TIMTOWTDI à la ternary operator:

print $condition1
      ? $condition2
        ? "All OK\n"
        : "Condition 1 true, Condition 2 false\n"
      :   "Condition 1 false\n";

Upvotes: 2

Pavel Vlasov
Pavel Vlasov

Reputation: 3465

You can use given..when if your version of Perl >= 5.10.

use v5.14;

my $condition1 = 'true';
my $condition2 = 'True';

given($condition1) {
    when (/^true$/) {
        given($condition2) {
            when (/^True$/) { say "condition 2 is True"; }
            default         { say "condition 2 is not True"; }
        }
    }
    default { say "condition 1 is not true"; }
}

Upvotes: 1

ysth
ysth

Reputation: 98508

The if condition 1 is true. The clause is missing its closing } which should be inserted right before the last else.

Try to line things up this way:

if (...) {
    if (...) {
        ...
    }
    else {
        ...
    }
}
else {
    ....
}

Upvotes: 2

Shan
Shan

Reputation: 1907

#OR condition
if ( ($file =~ /string/) || ($file =~ /string/) ){
}

#AND condition
if ( ($file =~ /string/) && ($file =~ /string/) ){
}

Upvotes: 0

librarian
librarian

Reputation: 129

How about:

if (Condition1=false) {
     print "Condition1 not true";
}
elsif (Condition2=True ) {
    print "All OK"; 
}
else {
    print "Condition1 is true but condition2 not";  
}

Upvotes: 1

Related Questions