Perl 5.10: Porting Guide

From AJS.COM

Jump to: navigation, search

Perl version 5.10 is the latest release of Perl as of the writing of this article. It introduces many new features, and while it's nominally backward compatible, there are many things that you might want to change in existing code in order to get up to date with 5.10.

Switch

If you use the Switch module, or you just have lots of chained if/elsif/else constructs, you may want to move to 5.10's switch (which is called "given"). For example, here's 5.8 using the Switch module:

use Switch;
my $fruit = 'apple';
switch ($fruit) {
  case 'apple'  { print "Red\n" }
  case 'banana' { print "Yellow\n" }
  case 'orange' { print "Orange\n" }
  else          { print "Unknown fruit\n" }
}

In 5.10 that would become:

use feature "switch";
my $fruit = 'apple';
given ($fruit) {
  when ('apple')  { print "Red\n" }
  when ('banana') { print "Yellow\n" }
  when ('orange') { print "Orange\n" }
  default         { print "Unknown fruit\n" }
}

The other benefit here is that, at least on my machine, the new form is almost exactly 10 times faster.

Smart matching

If you've read the above section on switch/given you'll already have seen smart matching, but you might not have recognized it. Here are some common cases in 5.8 code where you might want to convert to smart matching:

# Matching against a pre-compiled regular expression
# that is stored in a variable (possibly passed in)
my $regex = qr{^[a-z]};
if ($string =~ /$regex/) {
  print "Found match!\n";
}
# In 5.10 we don't have to create an enclosing
# regex to perform the match:
my $regex = qr{^[a-z]};
if ($string ~~ $regex) {
  print "Found match!\n";
}
# 5.8:
my $thing = "apple";
return "found" if grep {$_ eq $thing} @somelist;
# 5.10:
my $thing = "apple";
return "found" if @somelist ~~ $thing;

Defined or

The C<//> operator performs a "defined or" operation. This is almost exactly the same as the C<||> or operator and looks very similar in common usage:

 if ($a // $b) {
   ...
 }

However, it selects the first value only when it is defined. If it has any value, regardless of the true/false status of that value, it will be returned. If the left hand value is C<undef>, then it will return the right hand value. This has many practical applications where you would have used the somewhat cumbersome C<defined> operator:

sub send_mail {
  my($to,$from,$subject) = @_;
  $to //= 'root@example.com';
  $from //= 'postmaster@example.com';
  $subject //= "No subject provided";
  ...
}
die( $DBI::errstr // "DBI error" );
foreach (@somelist) {
  $_ // last; # stop on undefined value
}
Personal tools