Perl: a password (sort of) using regular expression (regex) power

The tutor shows off some of Perl’s pattern matching (aka regex) talents.

Let’s imagine you have a laptop you share with a friend for project work. They’re not million-dollar secrets you’re keeping, but on the other hand, you don’t want just anyone reading those files. At the same time, your friend is very forgetful, likely not to remember a typical password.

To accommodate your friend, while keeping out the casual snoops, you settle on a three-character password with a variable middle character. Let’s imagine the password is n[any character]n. Then, nan or n@n will succeed, but nano won’t (too long). Of course, the first and third characters must both be n.

Pattern matching is done using regular expressions, or regex.

Here is the Perl code that can accept the entry, then decide if it matches:

print “Enter your password, please.\n\n”;

$word=<STDIN>;

if ($word=~/^n.n$/){  #the regex line
print “Correct.\n”;
}

else{
print “Incorrect password; access denied.\n”;
}

I’ll be explaining some nuts and bolts of the regex line in a coming post:)

Source:

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Robert’s Perl tutorial

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: , , ,

Leave a Reply