Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to write a Perl program.The program is simple.If the variables $a and $b are equal to 1 then something is to be printed.But the catch is the program has to check for the value of $b only if $var == 1. Otherwise,if $ $var == 0,only $a value has to be checked.

I have tried to write it by using nested if.But I am getting errors.(I tried to do it the same way how it can be done in C by using MACROS.)

my $var = 1 ;

my $a = 1 ;
my $b = 1 ;

if(($a == 1)
{
if($var == 1 )
{
&& ($b == 1)
}

)

print " hey ,it worked " ;

}

Case:1 ) So,$var==1 ,it has to check for the value of $b before printing.

my $var = 1 ;

my $a = 1 ;
my $b = 0 ;

if(($a == 1)
{
if($var == 1 )
{
&& ($b == 1)
}

)

print " hey ,it worked " ;

}

Case:2 ) $b==0,nothing gets printed.

my $var = 0 ;

my $a = 1 ;
my $b = 1 ;

if(($a == 1)
{
if($var == 1 )
{
&& ($b == 1)
}

)

print " hey ,it worked " ;

}

Case : 3 )$var==0,it shouldn't check for the value of $b and the line is printed. I should get the above mentioned results.But I am not getting how to do it.Kindly Help.

Thanks for the replies.But you did not understand my question.What I really want to do is ,way back I had written a program in C where I will define the macro in .h file something like,

#define SWITCH 1

In .c file,I will check for the condition.

 if((a == 1)
#if SWITCH 
        && (b == 1)    
        )
       { 
        print " hey ,it worked " ; 
       }

So,here $b will be checked ,only if the macro value SWITCH is 1 in .h file.If the value is changed to 0,

#define SWITCH 0

then print statement depends only on the value of a and b value is not checked.I want to do the same thing in Perl.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
310 views
Welcome To Ask or Share your Answers For Others

1 Answer

This performs the check as you described it in English:

if ($var ? $a && $b : $a)

This is an equivalent check:

if ($a && ( !$var || $b ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...