OSCON 2008: Perl 5.10 For People Who Aren’t (Totally) Insane, by Ricardo Signes


There haven’t been any significant new features in Perl since 2002. This talk will give features that aren’t completely insane, aren’t just for the masters.

5.10 adds new operators and operators that will break when run under older versions of Perl, but they’re not enabled by default: use feature 'mtfnpy' and use 5.010.

say is a new builtin that is just like print, but it puts a newline at the end.

Truth and definedness is handled better than before:

sub record_sale {
  my ( $product, $amount ) = @_;
  $amount ||= $product->cost;
  ...
}

But what happens if the cost is zero? Then you had to use some ternary operator code. In 5.10 you can use the new “or” operator: $amount //= $product->cost;

State variables can replace a lexical or something messier, so you can do this:

sub read_line {
  state $lines_left = 100;
  die "trial period expired" unless $lines_left-- > 0;
  ...
}

The first time in, the variable gets initialized. Next time in, it doesn’t, and it keeps the value when it went out of scope.

File tests are now stackable: if( -f -w -z $file ) instead of if( -f $file and -w $file and -z $file ).

Smart matching is a new kind of comparison. It depends on the input to the operator. The smart match operator is ~~ and tries to figure out the right time of match. You can do $foo ~~ undef (check for definedness), $foo ~~ @array (it’s in the array), coderefs, in a hash (don’t know if that’s in keys or values though).

Perl 5.10 has a switch operator: given and when. It uses the smart matching to do its comparisons.

SmartMatch::Sugar does powerful smart matching.

Better error messages for “unknown undefined” values. When you do things like printing out variables and get the “use of uninitialized value” warning, it will tell you which variable is undefined.

Traditional Perl5 objects are made with a hashref. Looking up attributes means you look up the actual attribute name. In 5.10 you look up the attribute in an external hash by the object ID. This introduces a field hash:

sub size {
  my $self = shift;
  fieldhash state %size;
  if( @_ ) { return $self{$size} = shift; }
  return $self{$size};
}

Lexical $_ (he calls $_ “topic” because it’s easier to say). You can now do things like for my $_ (@lines) { ... } and when you leave scope, $_ doesn’t get changed when you might not expect it to (say if there’s a subroutine that modifies it).

Regular expression named captures: find matches by name, not by position. No more $1! Now you can do $line ~~ /(?\w+):(?\w+)/ so then you can access $name and $value instead of $1 and $2.

[tags]oscon, oscon08, perl[/tags]

  1. No comments yet.
(will not be published)