Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Passing logical operators on as content of scalar

by Marshall (Abbot)
on Feb 08, 2018 at 19:37 UTC ( #1208744=note: print w/replies, xml ) Need Help??

in reply to Passing logical operators on as content of scalar

Your code as written is easy to understand at a glance. However, I think you are missing a case in the '<' situation, where $number1 is equal to $number2?

I liked the post by Eily++. If I went that way, I likely would go further by incorporating the result of $number1 <=> $number2 into the hash key. That way there are no "if" statements at all in the calling code. Maybe resulting in a table like this?:

my $dispatch = {"< -1" => "num1 less than num2", "< 0" => \&actionX, # blah...blah 6 or 9 entries to cover all cases, <, >, +== times 3 };
In your "==" case, the dispatch action for $num1<$num2 and $num1>$num2 would be the same.
Note: I would have to read the spec carefully on the spaceship operator. Instead of it returning -1,0,1 which is what it actually does, it might be spec'd as only negative number,0,positive number. I would allow whatever the spec says is allowed (convert to -1,0,1 so that hash lookup works no matter what exact spaceship implementation is).

However having said that, the code structure that you have is easy to understand and it will execute very quickly (faster than a dispatch table). It took me a bit more "brainpower" to understand the Eily code whereas I understood your code at a glance. I wouldn't be overly concerned about "wordiness". If the pattern shown in your code repeats often elsewhere in the code, then the "understanding overhead" associated with the dispatch table is perhaps worth it. Simple, albeit it wordy code is often a good way to go. It is also possible that I might implement the three cases <,>,== with the same if logic (no special handling of ==). That would make the code even more wordy, but more "regular". Coding is part art and part science - lot's of ways to do things.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-08-16 04:39 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (166 votes). Check out past polls.