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";
exit;

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
6.4

Untainting

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);

Mojolicious with mod_fcgid

Mojolicious has a PSGI interface which means that you could use Plack or your other favourite implementation as the glue to serve a Mojolicious app via a traditional webserver. This becomes more problematic when using mod_fcgid as now your application is 2 steps removed. However, Mojolicious also has its own FCGI backend so we can use this directly with mod_fcgid if we are careful in how we configure it.

Suppose our application resides in /var/www/fcgi-bin/foo.fcgi and we want it called from the /myapp/ top-level URL path. The Apache configuration then should be

AddHandler                  fcgid-script .fcgi
FcgidMinProcessesPerClass   0
FcgidIdleTimeout            300
ScriptAlias                 /myapp /var/www/fcgi-bin/foo.fcgi

Choose other values for FcgidMinProcessesPerClass and FcgidIdleTimeout as appropriate. Then, ensure that foo.fcgi is executable by the user which Apache runs as and your foo.fcgi should look like this sample application.

#!/usr/bin/perl

use Mojolicious::Lite;

my $n = 0;

get '/' => sub {
	my $c = shift;
	$n++;
	$c->render (text => "Hello World ($n)!");
};

app->start ('fastcgi');

The argument to start() in the last line is the secret ingredient. Restart Apache to pick up the changes and your app should run persistently on-demand without requiring a separate back-end server or process manager.

Hash ref slice

You can use hash slices and you can use hash references but how can you use a hash ref slice? This is a very useful technique but the syntax can take some work to figure out.

my $href = { france => 'Paris', italy => 'Rome', japan => 'Tokyo' };
print "@$href{qw/france japan/}\n"; # prints "Paris Tokyo\n";

Similarly to how @hash{qw/onekey otherkey/} uses the @ sigil to return the hash slice as a list, the same sigil is used on the hashref. However, this time the $ sigil is also required in order to de-reference the hashref first (cf. %hash vs %$hashref).

More examples will be added to this page over time.