Command line arguments play a significant role in the creation of command line programs in any language. These arguments can tell the program a number of things, such as what to operate on, or how to operate on something. Perl, like most other languages, makes it very easy to read these arguments.
However, sometimes it's necessary to interact with a command line program differently. Sometimes, it's necessary to change a program's behavior in order to turn off or on functionality, or to adjust some setting in some way.
For example, consider the program cat. Using it, it's possible to print the contents of a given file to standard output:
$ cat file.txt
It's also possible to number the lines that are outputted. This is done with a command line option:
$ cat -n file.txt
Command line options, also known as flags or switches, make it possible to pass optional instructions to a command line program. Unlike command line arguments, however, these are a bit harder to read, especially since they can take a number of forms.
In this article, we'll take a look at a few ways to process command line options in Perl.
A short introduction
Before we get started with Perl code, let's take a minute to conduct a very basic overview of command line options. First, command line options can either be short or long. Short command line options are represented by a hyphen followed by a single letter (that's why they're “short”). Consider the example earlier:
$ cat -n file.txt
Above, we use a short command line option. Long options, on the other hand, can contains multiple letters and are usually preceded by two hyphens (although some applications use only one). Sometimes, an application allows both forms to be used. In fact, cat allows this. We could rewrite the last example like this, to use a long option:
$ cat --number file.txt
Command line options can serve in an on/off role, or they can have values after them. The number option above is an example of on/off behavior. In that case, we're turning numbering on. All that's needed for this behavior is the name of the option.
If an option has a value after it, the placement of that value may differ depending on whether the option is short or long. For a short option, the value may be placed with a space between the option name and the value:
$ ls -T 1
Or, if the value is a number, then it may come immediately after the option name:
$ ls -T1
For a long option, the value is placed after an equals sign:
$ ls --tabsize=1
Also, if there are multiple short options with no values associated, they may be spaced out:
$ cat -n -v file.txt
Or, more commonly, they can be combined, with no spaces in between:
$ cat -nv file.txt
This is known as “bundling.” The key thing to remember, though, is that bundled options do not have values.
blog comments powered by Disqus