Perl 5.10 - My Favourite Three Features

Since the release of Perl 5.10 (back on 2007/12/18) there have been a fair few articles discussing all the shiny new features - including smart matching, a built-in switch and state variables but my favourite three haven’t really received much coverage. So I’ll add to the pile of blog posts.

First up is a tiny (from the outside anyway) change that may have the biggest impact of all the new features on my day to day perl - the display of the actual name of uninitialized variables.

# older perls
$ perl584 -we 'print $foo, "\n";'
Use of uninitialized value in print at -e line 1.

# perl 5.10
$ perl510 -we 'print $foo, "\n";'
Use of uninitialized value $foo in print at -e line 1.

From the perspective of someone who has to spend the occasional afternoon reading Apache errorlogs I really like this one.

Now we move on to stackable file tests; something I was surprised perl couldn’t do when I first noticed it was missing years ago -

# older perls
...
if (-s $file && -r _ && -x _) {
  print "$file isn't zero length and is +rx\n";
}
...

# perl 5.10
...
if (-s -r -x $file) {
  print "$file isn't zero length and is +rx\n";
}
...

Lastly on my little list is named captures - instead of referencing $1 and $2 etc. you can now assign them names at the point of capture and then pull the values out of a hash at a later time

# requires 5.10 or above. But not 6.

my %date;
my $sample_date = '20071225';

if ( $sample_date =~ /(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})/ ) {
  %date = %+;
}

say "The year is $date{'year'}";

While none of these are massive attention grabbing additions like the powerful smart matching, switch statement or say (one of those is not like the others ;)) they help make the day-to-day stuff a little more pleasant.

Bonus feature -

my $x;
my $default = 'foo';

$x = 0;
$x ||= $default; 

say "\$x is $x";

$x = 0;
$x //= $default;

say "\$x is $x";