Perl Programming Page 2 - Scalars and Boolean and String Operators |
The first simple comparison operator is ==. Two equals signs tells Perl to “return true if the two numeric arguments are equal.” If they’re not equal, return false. Boolean values of truth and falsehood aren’t very exciting to look at, but let’s see them anyway: #!/usr/bin/perl -w print "Is two equal to four? ", 2 == 4, "\n"; This will produce $ perl bool1.pl This output shows that in Perl, operators that evaluate to false evaluate to the empty string ("") and when true evaluate to 1. The obvious counterpart to testing whether things are equal is testing whether they’re not equal, and the way we do this is with the!= operator. Note that there’s only one=this time; we’ll find out later why there had to be two before. #!/usr/bin/perl -w print "So, two isn't equal to four? ", 2 != 4, "\n"; $ perl bool2.pl There you have it, irrefutable proof that two is not four. Good. Comparing Numbers for Inequality So much for equality, let’s check if one thing is bigger than another. Just like in mathematics, we use the greater-than and less-than signs to do this: < and>. #!/usr/bin/perl -w print "Five is more than six? ", 5 > 6, "\n"; The results should hopefully not be very new to you: $ perl bool3.pl Let’s have a look at one last pair of comparisons: we can check greater-than-or-equal-to and less-than-or-equal-to with the>=and<=operators respectively. #!/usr/bin/perl -w print "Seven is less than or equal to sixteen? ", 7 <= 16, "\n"; As expected, Perl faithfully prints out $ perl bool4.pl There’s also a special operator that isn’t really a Boolean comparison because it doesn’t give us a true-or-false value; instead it returns 0 if the two are equal, –1 if the right-hand side is bigger, and 1 if the left-hand side is bigger—it is denoted by<=>. #!/usr/bin/perl -w print "Compare six and nine? ", 6 <=> 9, "\n"; gives us $ perl bool5.pl The<=>operator is also known as the spaceship operator or the shuttle operator due to its shape. We’ll see this operator used when we look at sorting things, where we have to know whether something goes before, after, or in the same place as something else.
blog comments powered by Disqus |
|
|
|
|
|
|
|