Skip to main content

Simple PERL Invocation Options

By June 19, 2017September 12th, 2022No Comments

simple PERL invocation optionsPERL is not the newest of languages and that it most certainly true. However, just because something is not new it does not automatically mean it is depreciated. In this lesson we will look at using PERL and keeping the code simple and clean. To do this we will use simple PERL invocation options. These options can be used directly from the CLI or part of your shebang in a script.

PERL is great choice for scripting as it installed by default on most Linux distros, including minimal installs. Even though it does have a following that think the language is verbose we can show how through the use of simple PERL invocation options we can make the code very light and very simple. Firstly we can check PERL is installed and the version:

$ perl -v

Now lets speak a little computer and say the ubiquitous “Hello World”. We can execute code from the CLI with -e (not required in scripts). The options -w is a good one to use as it prints warnings when we may have made some errors.

ubuntu@alice:~$ perl -w -e 'print "Hello World";'
Hello Worldubuntu@alice:~$

Now the more experienced among you may have predicted this, without adding a new line to print the output and prompt are now on the same line. We would normally add in a newline when using print.

ubuntu@alice:~$ perl -w -e 'print "Hello World\n";'
Hello World

This though makes the code more verbose and cluttered, also, it is likely that we will have more than one print statement so the new line is going to be repeated. Then we don’t add the \n many times. We use simple PERL invocation options to do this for us, and just once. We use -l:

ubuntu@alice:~$ perl -wl -e 'print "Hello World";'
Hello World

Next we see how easy it to process and filter files. Whilst I can write verbose code to open a file, I don’t need to.

ubuntu@alice:~$ perl -wlp -e '' /etc/passwd

The option -p comes into play here where we can print each line from STDIN. This is the file /etc/passwd in this case. Notice the code block for PERL is empty, just two single quotes. If we want to do more than just print the file we can work with the content. Here we only print the line that contains the ubuntu user. We avoid using an if statement for the more simple logical and. We also swap the -p option for -n. We don’t want to print all lines just the lines that we match, so we code this with our own print statement:

ubuntu@alice:~$ perl -wln -e '/ubuntu/ and print;' /etc/passwd

The video follows, please enjoy.