Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Control Structures

by Eimi Metamorphoumai (Deacon)
on May 10, 2005 at 16:33 UTC ( [id://455650]=note: print w/replies, xml ) Need Help??


in reply to Control Structures

It's hard to look outside the box, almost by definition. So what follows aren't really suggestions for syntax, they're more questions for "what's a good idiom for?"

The "loop-and-a-half" problem has already been mentioned, but I still haven't seen anything that looks really good (though the redo aproach may be the cleanest).

Something I've frequently found myself doing is wanting a three-way control structure for greater than, less than, and equal to. Sure there are ways to do it, but none of them really feel clean.

given fork { case $_ < 0 { #error } case $_ > 0 { #parent } default { #child } }
or
if ((my $pid = fork()) < 0){ #error } elsif ($pid > 0) { #parent } else { $child }
But it's the sort of thing that feels like it could be simpler. A better example might be checking two values against each other, where it feels unnatural to need a separate variable or compare them multiple times.
if (get_the_boundary_x() < the_user_provided_x()){ draw_color("green"); elsif (get_the_boundary_x() == the_user_provided_x()){ draw_color("blue"); else { draw_color("red"); }
(Yes, I know that can be done with draw_color(qw( blue red green )[get_the_boundary_x() <=> the_user_provided_x()], but that's just ugly and confusing).

merlyn's looking for a good idiom: return this if this is true shows another question without a (really good, or at least completely natural) answer. The suggested if (my $ret = thatroutine()){return $ret} feels ugly due to the synthetic variable $ret.

Replies are listed 'Best First'.
Re^2: Control Structures
by merlyn (Sage) on May 10, 2005 at 17:10 UTC
    First, fork doesn't return -1 on error. It returns undef. Perhaps you were thinking of something else. (I hope that's not the way you've been coding your fork checking all this time!)

    Second, as one odd way to solve your problem, you could execute one of a few code blocks:

    ( sub { print "A is less than B" }, sub { print "A is equal to B" }, sub { print "A is greater than B"} )[($a <=> $b) + 1)]->();
    OK, maybe not much better, but at least you don't compute it more than once.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://455650]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-24 11:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found