Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Seeing if two numbers have the same sign

by Anonymous Monk
on Jan 11, 2008 at 16:59 UTC ( [id://661913]=note: print w/replies, xml ) Need Help??


in reply to Seeing if two numbers have the same sign

Don't code “clever!” The simplest and most expressive code is always best:

sub same_sign { my ($x,$y) = @_; if ( undef($x) or undef($y)) { return 0; # "undef" is never same-sign } if ( ( ($x >= 0) and ($y >= 0) ) or ( ($x < 0) and ($y < 0) ) ) { return 1; } else { return 0; } }

Is this (caution: extemporaneous Perl...) module terse? No. Could it have been written with fewer characters? Yes. But neither of those considerations are “the point.” What matters to me is that it is obvious what this code is actually supposed to do. Everything about it, including the white space, is designed to encourage readability among humans. The Perl compiler can take care of itself.

Replies are listed 'Best First'.
Re^2: Seeing if two numbers have the same sign
by Corion (Patriarch) on Jan 11, 2008 at 17:02 UTC

    I suggest you test your code before posting:

    use strict; sub same_sign { my ($x,$y) = @_; if ( undef($x) or undef($y)) { return 0; # "undef" is never same-sign } if ( ( ($x >= 0) and ($y >= 0) ) or ( ($x < 0) and ($y < 0) ) ) { return 1; } else { return 0; } } $\ = "\n"; print same_sign(1,1); print same_sign(0,0); print same_sign(undef,undef); print same_sign(-1,-1); print same_sign(-2,-2); print same_sign(2,-2); __END__ 1 1 1 1 1 1

    Your subroutine seems to suggest that all values passed in always have the same value sign...

    Update: Correction thanks to lodin
Re^2: Seeing if two numbers have the same sign
by demerphq (Chancellor) on Jan 11, 2008 at 19:34 UTC

    You probably meant !defined() where you put undef().

    And personally i think your code is much harder to understand than what i posted. Longer is very often less comprehensible than shorter for the simple fact that most people can only operate on a small number of items at a time. (8 or so).

    ---
    $world=~s/war/peace/g

      You probably meant 5..9 where you put (8 or so). :-)

        Yes. I probably did. :-) Good link BTW.

        ---
        $world=~s/war/peace/g

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 09:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found