Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

Multiple Conditions Check in Perl

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

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

1 Reply

0 votes
by (71.8m points)

This performs the check as you described it in English:

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

This is an equivalent check:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...