PDA

View Full Version : Short Hand If Statements


gold_dragon
02-04-2004, 07:06 PM
Ok, I thought I have seen reference to the ? : short hand if statements through when I tried it out, it didn't work correctly. It appears that I jumped passed the code and excuted the last statement on the line.($_ != $#ARR) ? $b = $_+1 : $b = 0; I have even tried it with the semicolon after the $b=$_+1 and it still didn't work. I have looked elsewhere and saw that one of the programmers used the '&&' instead of the if...else...elsif to save space and typing. If anyone knows the correct syntax to do this then it would be helpful. If there is none then I will beat myself of the head and if not then it should be something to add to the programming language.

There should be at least more than one way do this since Perl is known for this feature (fact?).

Whiteknight
02-06-2004, 11:16 PM
its called a conditional statement, and i know that it is implemented in C, although i have never seen it in perl. i wonder if the syntax is different.

other then that, you have the correct syntax methinks.

little birdy
02-10-2004, 03:25 PM
that's not how the ternary operator was intended to be used. if you want to conditionally execute whole statements, like $b = 0 or print "something", etc, then use if/else. the ternary operator returns something, so you should use it like this: $b = ($_ != $#ARR) ? $_ + 1 : 0;

and if that also won't work, then perl either doesn't support it, or has put a weird spin on it.

Whiteknight
02-10-2004, 05:15 PM
i used to nest alot of conditionals in printf statments, so that i could get a decision made as the text was printing, so yeah, i dont think it works exactly like an if else statement.

gold_dragon
02-12-2004, 08:15 AM
Originally posted by Whiteknight
i used to nest alot of conditionals in printf statments, so that i could get a decision made as the text was printing, so yeah, i dont think it works exactly like an if else statement. The funny thing is that it didn't complain about the syntax. Of course it just skipped over everything and always did the last statement. I guess that is the way Perl works. Of the course, the funny thing was when I switched the operators, it give me a funny error so I think it works.