| | |||||||
| |||||||
| |||||||
|
|
|
|
|
|
|
Comparing Strings with Control Flow Constructs(Page 1 of 2 ) In this third part of a nine-part article series on Perl control structures, we'll examine the operators used ot compare strings. This article is excerpted from chapter three of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X). Comparing Strings When we’re comparing strings, we use a different set of operators to do the comparisons as listed in Table 3-2.
Here’s a very simple way of testing if a user knows a password. Note: don’t use a good password in this program since the user can just read the source code to find it! #!/usr/bin/perl -w use strict; my $password = "foxtrot"; Here’s our security system in action: $ perl password.pl This program starts by asking the user for input: my $guess = <STDIN>; Just a warning: this is a horrendously bad way of asking for a password, since it’s echoed to the screen, and everyone looking at the user’s computer would be able to read it. Even though you won’t be using a program like this, if you ever do need to get a password from the user, the Perl FAQ provides a better method in perlfaq8. Typeperldoc -q passwordto find it. chomp $guess; This statementchomps the newline off of$guess. We must never forget to remove the newline from the end of the user’s data. We didn’t need to do this for numeric comparison, because Perl would remove that for us anyway during conversion to a number. Otherwise, even if the user had entered the right password, Perl would have tried to compare"foxtrot"with"foxtrot\n"and it could never be the same. if ($password ne $guess) { Then if the password we have isn’t the same as the user’s input, we send out a rude message and terminate the program. More Programming Basics Articles |
| |
| |