Perl Programming Scalars and Variables |
String Comparison As well as comparing the value of numbers, we can compare the value of strings. This does not mean we convert a string to a number, although if you say something like"12" > "30", Perl will convert to numbers for you. This means we can compare the strings alphabetically: “Bravo” comes after “Alpha” but before “Charlie”, for instance. In fact, it’s more than alphabetical order; the computer is using either ASCII or Unicode internally to represent the string, and so has converted it to a series of numbers in the relevant sequence. This means, for example, “Fowl” comes before “fish”, because a capital “F” has a smaller ASCII value (70) than a lowercase “f” (102).1 1. This is not strictly true, though. Locales can define nonnumeric sorting orders for ASCII or Unicode characters that Perl will respect. We can find a character’s value by using theord()function, which tells us where in the (ASCII) order it comes. Let’s see which comes first, a#or a*? #!/usr/bin/perl -w print "A # has ASCII value ", ord("#"), "\n"; This should say $ perl ascii.pl If we’re only concerned with a character at a time, we can compare the return values oford()using the Instead, there are string comparison operators that do this for us. Whereas the comparison operators for numbers are mathematical symbols, the operators for strings are abbreviations. To test whether one string is less than another, uselt. “Greater than” becomesgt, “equal to” becomeseq, and “not equal to” becomesne. There’s alsogeandlefor “greater than or equal to” and “less than and equal to.” The three-way-comparison becomescmp. Here are a few examples of these: #!/usr/bin/perl -w print "Which came first, the chicken or the egg? "; And the results: $ perl strcomp1.pl The last line prints nothing as a result of"^" lt "+"since this operation returns the empty string indicating false. Be careful when comparing strings with numeric comparison operators (or numeric values with string comparison operators): #!/usr/bin/perl -w print "Test one: ", "four" eq "six", "\n"; print "Test two: ", "four" == "six", "\n"; This code produces $ perl strcomp2.pl Is the second line really claiming that"four"is equal to"six"? Yes, when treated as numbers. If you compare them as numbers, they get converted to numbers."four"converts to 0,"six"converts to 0, and the 0s are equal, so our test returns true and we get a couple of warnings telling us that they were not numbers to begin with. The moral of this story is, compare strings with string comparison operators and compare numbers with numeric comparison operators. Otherwise, your results may not be what you anticipate.
blog comments powered by Disqus |
|
|
|
|
|
|
|