Smarter scripts: Multiple options

  1. Exiting loops ahead of time
  2. Smarter scripts
  3. Script confusion

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.

It we want that, it makes sense to create a --format switch that can take only two options: raw and (say) simple. Add the following lines to the switch section:

} elsif ($switch eq "format") {
$format = shift;
if ($format ne "raw" && $format ne "simple") {
print "\nFormat must be raw or simple.\n\n";
help();
exit;
}
}

Pretty normal stuff here. The letters “ne” stand for “not equal” to. So, if the user specifies a format that is not raw and that is not simple, the script displays the help and exits.

Now, replace the line that prints the song information with:

if ($format eq "raw") {
print;
} else {
print "$song ($album, by $artist)\n";
}

What we’re really doing here is printing the current line if the user specified a format of raw, and printing the simpler information in every other case. But this may change later if we add more formats. You will usually want to include the default as an option, just in case you make changes later.

./show --limit 12 --format raw aerosmith songs.txt

./show --limit 12 --format simple aerosmith songs.txt

If you were filtering out information to a new file, you might do this to redirect the output to that file:

./show --format raw aerosmith songs.txt > aerosmith.txt

./show love aerosmith.txt

You can also type “more aerosmith.txt” to verify that it has what you expect: all songs by Aerosmith.

You’ll want to add format to the help subroutine:

print "\t--format <raw or simple >: choose format for results\n";

  1. Exiting loops ahead of time
  2. Smarter scripts
  3. Script confusion