Here are some examples of using perl code. These examples serve to demystify some aspects of the language, illustrate best practice in perl programming or simply demonstrate how this powerful tool can be used to accomplish tasks in a quick and flexible manner.

Or what?

It is sometimes confusing to the programmer that there are two "OR" operators in perl. Here we seek to remove some of that confusion by some simple examples.

Override if untrue

If we want to set a default value for a variable in situations where the user may or may not have provided their own value we can use the || operator thus:

use strict;
my $dogname = $ARGV[0] || 'Rover';
print "My dog is called $dogname.\n";

Equally, we can use the handy ||= operator when a scalar can have a true value.

sub foo {
  my ($dogname, $dogfood, $walkies) = @_;
  $dogname ||= 'Rover';
  print "My dog is called $dogname.\n";

Note that in both of the above cases it is only the trueness of $dogname which is being tested and not the definedness, so a perfectly well defined but untrue value would be clobbered.

Execute on failure

Conversely we can use the or operator when we wish to test the result of an operation rather than a value. For example:

use strict;
my $log = '/var/log/messages';
open my $logfh, '<', $log or die "Error opening $log: $!\n";

Technical differences

While these examples have served to highlight when one might prefer to use one or other of these operators, it is important to understand why. The difference comes in the precedence: the or operator has a much lower precedence than ||. For this reason, although either could be used in the above examples if they were used the other way round, brackets would be required in the situation where operator precedence would otherwise cause unexpected actions.

Which version is installed?

Sometimes you just want to know which version of a module is installed on the current machine. There are any number of ways to determine this, but a reliable and simple way for bash users is with this simple function defined in your .bashrc:

pmv () { perl -M$1 -e "print \$$1::VERSION . qq/\n/;"; }

The function can then be called from the command prompt:

$ pmv Date::Calc


Nobody wants to write four lines where one would suffice (so long as the meaning of the code remains clear, of course). So, here is the simplest method of reliably untainting properly checked data.

($foo) = ($var =~ /someregex/g);