Perls Before Swine: Smarter scripts
- The basic Perl filter
- Perls Before Swine
- Arrays and functions
- Capturing errors
- It isn’t that difficult to trip up the script we’ve got so far. If you just type ./show and press return, not only does it wait on the command line for us to type something, it doesn’t even know that we didn’t tell it to search for anything.
- Smarter scripts: Help!
- One of the advantages of subroutines is that partitioning off some Perl lines allows us to call those lines from multiple places without having to retype the lines. This improves the readability of our script and also the reliability. If we make a mistake in the subroutine, we can fix it in the subroutine.
- Command-line switches
- So now we have a script with one command-line switch, but switches are like potato chips: once you start, you can’t have just one. Here’s an example: we’ve currently made our script case-insensitive, so that we don’t have to worry about remembering the exact case of the text we’re looking for. But what if we want it to be case-sensitive? Let’s add a case switch.
- Case sensitivity
- 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.
- Boolean logic
- 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…
- Exiting loops ahead of time
- Often when we’re testing we don’t really want to see everything, we just want to see that it worked. The first several results will let us know that. Let’s put in a switch to limit the number of results to a specified maximum. We’ll call this switch limit and it will be followed by a number.
- Multiple options
- Some switches will have a small list of options to choose from. For example, we modified our script to display the song information in a more human-readable format. But what if we want to keep the raw format under some circumstances? Maybe we want to take the raw song listing, filter out some albums we no longer have, and then create a new raw listing from that filter.
- Script confusion
- What happens if you misspell a switch? Try:
- The current script
- Just so we’re on the same page, here is what the script currently looks like: