Smarter scripts: Case sensitivity

  1. Command-line switches
  2. Smarter scripts
  3. Boolean logic

So after all that, we still haven’t added case sensitivity to the script. But now, we can add pretty much anything we want. Our switch is going to be called case. What we’ll do is set $sensitive if we want the search to be case sensitive.

Replace the closing curly bracket where we’re checking for the help option with:

} elsif ($switch eq "case") {
$sensitive = 1;
}

The whole switch section should look like:

if ($switch eq "help") {
help();
exit;
} elsif ($switch eq "case") {
$sensitive = 1;
}

This is pretty simple, so far. If the command-line switch is “--case” then assign the number 1 to the variable $sensitive.

Replace the line that prints out the song information with:

if ($sensitive) {
$matched = /$searchFor/;
} else {
$matched = /$searchFor/i;
}
#print the information if this line contains our search text
print "$song ($album, by $artist)\n" if $matched;

If $sensitive has something in it, we match without the case-insensitivity modifier. Otherwise, we match with the case-insensitivity modifier. We assign the result of that match to $matched, and then if $matched has something in it we print the song information. (You might ask why we don’t just create a variable that either has “i” in it or not. The answer is that we can’t do that. A variable won’t work in that part of a regular expression.)

Now, you can search for:

./show --case Yellow songs.txt

./show --case yellow songs.txt

And get different results. Add the help line to the help subroutine and we’re done with this option:

print "\t--case: be sensitive to upper and lower case\n";

  1. Command-line switches
  2. Smarter scripts
  3. Boolean logic