Is there a way to use the <=> operator in a perl if statement?

  • A+

To start off with, I realize that I can write an if statement with this operator that compiles and runs. I'm wondering if there's a way it can be used to make an if/elsif/else block a little more elegant.

I currently have a block of code that looks like this

 if( $bill == $ted) {         # Do some stuff } elsif( $bill < $ted) {         # Do different stuff } else {         # Do really weird stuff } 

So there are specific things I want the script to do based on whether the two values are equal, or if they aren't equal, whichever one is lower. It seems like the <=> operator would be well suited to this.


Well, the operator returns 1, 0 or -1 depending on the test outcome, which is what sort uses.

So it's quite viable to do that. But I'm not sure if it's a particularly clear approach, compared to;

if ( $first < $second ) { do X ; next} if ( $first > $second ) { do Y ; next} do Z. #$first == $second 

I'd strongly suggest avoiding single letter variable names, and most especially $a and $b. It's poor style, and $a and $b are used by sort which could lead to confusion.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: