Smarter scripts: Boolean logic

  1. Case sensitivity
  2. Smarter scripts
  3. Exiting loops ahead of time

So far our search has been for things that match. But sometimes filters are useful to filter out rather than filter in. We can add a switch that will cause the script to print out only those songs that don’t match the search. To do this, we’re going to need to understand Boolean logic. In case you’ve forgotten your Boolean logic from high school, it is basically about true and false. Perl treats items that contain something other than zero as true. It treats items that contain zero or nothing as false.

Code in your if or while parentheses are treated by Perl as Boolean expressions, as true or false.

You can reverse something from false to true or true to false with NOT, which in Perl is the exclamation point.

First, add the switch to our list of switches:

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

Then, add some new code to the while loop, after we assign a match or lack thereof to $match, but before we print the song information:

#reverse the match if we want non-matching lines
if ($reverse) {
$matched = !$matched;
}

You might also want to change the comment in front of the print line:

#print the information if this line is one we want

And, of course, add a line to the help subroutine:

print "\t--reverse: filter out songs that contain the search text\n";

So, now, if you want to see every song that does not mention best anywhere, use:

./show --reverse best songs.txt

Well. That showed a lot. Let’s see if we can do something about that.

  1. Case sensitivity
  2. Smarter scripts
  3. Exiting loops ahead of time