473,414 Members | 1,777 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

Mr. Ternary is greater than Mrs. If Else

hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma.

codes as follows using Mrs. If Else:

Expand|Select|Wrap|Line Numbers
  1. #!perl/bin/perl
  2.  
  3. use strict;
  4.  
  5. print "Are you sure you want to quit ('yes' or any key for 'no'): ";
  6. chomp($_ = <STDIN>);
  7.  
  8. if (/\byes\b/i) {
  9.     print "Press any key to exit...";
  10.     <STDIN>;
  11.     exit;
  12. }
  13. else {
  14.     print "Thanks, you stayed... But then, goodbye.\n";
  15.     print "Press any key to proceed...\n";
  16.     <STDIN>;
  17. }
  18.  
  19. print "GOOD DAY";
equivalent codes for Mr. Ternary as follows:

Expand|Select|Wrap|Line Numbers
  1. #!perl/bin/perl
  2.  
  3. use strict;
  4.  
  5. print "Are you sure you want to quit ('yes' or any key for 'no'): ";
  6. chomp($_ = <STDIN>);
  7.  
  8. /\byes\b/i ?
  9. eval {
  10.     print "Press any key to exit...";
  11.     <STDIN>;
  12.     exit;
  13. }
  14. :
  15. eval {
  16.     print "Thanks, you stayed... But then, goodbye.\n";
  17.     print "Press any key to proceed...\n";
  18.     <STDIN>;
  19. };
  20.  
  21. print "GOOD DAY";
Advantages of Mr. Ternary over Mrs. If Else:

1. shorter code
2. permits the parenthesis not to be used in the expression
3. permits the curly braces not to be used (well in here, eval takes its place. and note if you put an eval over Mrs. If Else, then Mr. Ternary is more appropriate)
4. promotes runtime error handling (the program doesn't exit so sudden)
5. the statements are more clearer to understand after a true or false evaluation

Disadvantages of Mr. Ternary:

1. difficulty in reading (only for the first timers because this is not conventional)
2. the return value of eval cannot be assigned to another variable (but there is the special variable $@ that holds it for you. you can evaluate that after the ternary operation)
3. tedious in bullet proofing a program (it is because you cannot quickly notice the runtime error inputted by the end user or file. in which Mr. Ternary uses the eval. it happens when your statements are so lenghty inside the eval block. but here is a solution for that, see next)

optional code revisions while bullet proofing:

Expand|Select|Wrap|Line Numbers
  1. #!perl/bin/perl
  2.  
  3. use strict;
  4.  
  5. print "Are you sure you want to quit ('yes' or any key for 'no'): ";
  6. chomp($_ = <STDIN>);
  7.  
  8. /\byes\b/i ?
  9. \& {
  10.     print "Press any key to exit...";
  11.     <STDIN>;
  12.     exit;
  13. }
  14. :
  15. \& {
  16.     print "Thanks, you stayed... But then, goodbye.\n";
  17.     print "Press any key to proceed...\n";
  18.     <STDIN>;
  19. };
  20.  
  21. print "GOOD DAY";
the only code was changed in here was "eval" to "\&"... now my delimma goes here... i don't know whats "\&" for. i just seen it on the Perl documentation under the strict pragma, and i read what it says "There is one exception to this rule...\& is allowed so that goto &$AUTOLOAD would not break under stricture.". well im just a novice programmer with Perl i don't really understand that. so what does "\&" mean?

back to Mr. Ternary, i think there is just only one slight drawback in using the ternary operator. that is difficulty in reading. but then its easy to overcome. so in other words Mr. Ternary is more handy than Mrs. If Else. so i think Mrs. If Else should be dropped from our system.

but then, if you have other downs in mind on Mr. Ternary, your statements will be gladly evaluated, then i will give you the output.

thanks in advance... keep deep and dark!

From: PerlPhi
May 19 '07 #1
5 3539
KevinADC
4,059 Expert 2GB
Certainly eval has it's advantages. But what happens if someone enters:

exec "shred --remove";

into your eval blocks?
May 19 '07 #2
Certainly eval has it's advantages. But what happens if someone enters:

exec "shred --remove";

into your eval blocks?
well i tried that, but everything just happens so normal... well i think nothing well really go wrong if i inputted that on whatever <STDIN> i go... because i didn't used any value of <STDIN> except for pattern match only...
May 19 '07 #3
KevinADC
4,059 Expert 2GB
Actually you're correct. I didn't really take the time to look at your code. It is safe as it is.

But.... your original question of why it seems the ternary operator is not used as much as you might think it could be, I am not sure why that is. My guess is that many perl programmers you come across on forums or in a class setting just never got used to using it or don't understand how to use it or have better alternatives. But also, your example of the ternary operator does not looks like less code/typing to me.
May 19 '07 #4
miller
1,089 Expert 1GB
Hello PerlPhi,

A very amusing post. However, there are a few misconceptions from the very beginning.

1) "i was wondering why do some programmers rarely uses the ternary operator"

The primary reason why people don't use the ternary operator is lack of exposure. As in perl, there always more than one way to do things, and the ternary operator is one of those things that has obvious replacements, namely the if construct. It's generally not until people learn how to code modules and start examining more profession code that they learn about the ?: operator and how it can be used to make cleaner code.

2) "wherein it is less typing indeed"

It is less typing, but it's not THAT much less typing. The primary instance where it becomes obviously useful is when a variable is being initialized based off of some conditional. In this situation, you'll sometimes see beginning programmers do some type of if construct.

Expand|Select|Wrap|Line Numbers
  1. my $var;
  2. if ("some condition") {
  3.     $var = "value 1";
  4. } else {
  5.     $var = "value 2";
  6. }
  7.  
In this case, the code can be simplified a lot and made more readable by using the ternary operator.

Expand|Select|Wrap|Line Numbers
  1. my $var = "some condition" ? "value 1" : "value 2";
  2.  
There are lots of other instances where it's use is obviously beneficial, but I won't bother listing those.

3) "i believe in the classic virtue of Perl which is laziness."

Wrong.

In no way should you consider this a perl virtue. This is a common stereotype of perl hackers. But perl programmers do not perscribe to this a characteristic.

Just because there is more than one way to do it, does not mean that each way is equally prefered. There is often a single method that balances readability, maintainability, efficiency, assumed risk, all of the primary concerns of programming.

Using the ternary operator in the way that you have demonstrated is not good. This is what the if construct is for.

Conclusion)

It's definitely entertaining to experiment with all the different ways that you can accomplish the same task in perl. But I encourage you to not use something simply because you can. Make sure there is a reason behind it. And hopefully a good reason. Making code 2 characters shorter is not a worthwhile endevour unless you're doing golfing. And that's never something that you should use for production code.

Keep the interesting observations coming.

- Miller
May 21 '07 #5
prn
254 Expert 100+
3) "i believe in the classic virtue of Perl which is laziness."

Wrong.

In no way should you consider this a perl virtue. This is a common stereotype of perl hackers. But perl programmers do not perscribe to this a characteristic.
Let me say right off the bat that I generally agree with miller's points here, but I will point out the three "great virtues" of a programmer (from the Camel book, I have the 3rd edition in front of me, but I'm pretty sure it was in earlier editions too):

Laziness
The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer.

Impatience
The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least that pretend to. Hence, the second great virtue of a programmer.

Hubris
Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer.
Now, of course these terms and descriptions were obviously selected with more than a bit of humor intended and the applications of the terms as Wall, Christiansen, Orwant and Schwartz (or whatever combination or subset of them came up with these) intended them are NOT the stereotypical applications of terms like "laziness", but properly understood, "laziness" is definitely a virtue. :)

But miller is certainly right, too, that "laziness" is NOT a virtue if the word is interpreted to mean just saving a couple of keystrokes. There's always more than one way to do anything, but miller points out correctly that they are not simply interchangeable. There are also lots of reasons to make good choices among those different ways of doing things and saving one or two keystrokes is rarely a good reason. The ternary operator can clarify or it can obfuscate. Always strive for clarity! "Laziness" as a virtue requires a longer-term outlook, not just a narrow view.

Paul
May 22 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Phil Powell | last post by:
$sortBy = ($_POST) ? $_POST : ($_GET) ? $_GET : 1; This script should set $sortBy to the $_POST or the $_GET or the default of 1 in one line. I do not want to have to do this:
2
by: zipher | last post by:
It seems the debate over PEP 308 (if-then-else expression) occurred prior to the arrival of generator expressions. Mightn't this new latter syntax be the ticket to a "one obvious way" to write a...
2
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this With regards,...
24
by: gupta.keshav | last post by:
HI, Is there any situation which can be handled by ternary operator but not with if else blocks? Thanks Keshav
6
by: glongword | last post by:
As the assert macro should evaluate to a void expression, it should not have an 'if statement' in its definition. Does this necessitate the existence of a ternary conditional operator? Is there a...
7
by: Bonj | last post by:
In making a ternary search tree to identify as fast as possible the type of word passed in to the algorithm, for instance sp_help -> 1 (procedures), select -> 2 (keywords), sysobjects -> 3 (system...
48
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any...
15
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.