Perl Programming/Perl 5.10 Additions

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

Perl 5.10[edit]

Perl 5.10 was a release version of the perl programming language that included a few new special features. Around the same time that Perl 5.10 was being prepared, design was moving forward rapidly in the design of the new Perl 6 language. Perl 6 was going to be very different from Perl 5, but in some ways still very much the same.

Because the two versions were being designed simultaneously, and because some of the same people were involved in both design processes, the two share a few features. From the exchange, Perl 5.10 got the smart-match operator, a switch-style given-when control structure, a defined-or operator and state variables, plus a number of internal performance enhancements.

Smart Match Operator[edit]

The smart match operator is like == and eq and =~ all crammed together, with a few extra features added as well. Smart match determines whether two objects match, regardless of what type of objects you throw at it.

Given - When[edit]

Perl finally has a switch-like statement built into the language. Instead of using the popular switch and case keywords found in C, Perl 5.10 uses given and when.

For instance:

my $option = 3;
 
given ($option) {
    when (0) { say 'Option 0 is chosen!'; }
    when (1) { say 'We have an option 1 here'; }
    when (2) { say 'Option is 2'; }
}

Perl's given/when construct is much more powerful than C's switch/case construct, however. Rather than just allowing integers as the match criteria for each when clause, strings, regular expressions, and even arrays are allowed. For instance:

my $name = 'Superman';
 
given ($name) {
    when ('Batman') { say 'Da na na na na na na na ... BATMAN!'; }
    when ('Superman') { say "It's a bird, it's a plane..."; }
    when (/woman/) { say 'Good day miss'; }
}

Defined-Or[edit]

Consider the oft-used code fragment:

if(!defined($thing)) {
   $thing = $new_thing;
}

or, the more idiomatically-perl version:

$thing = $new_thing unless(defined($thing));

Since this is so common, it was determined to make it into it's own operator: the defined-or operator:

  $thing //= $new_thing;

State Variables[edit]

Perl 5.10 introduced the state keyword to declare persistent variables that retain their values between calls to a subroutine. State variables serve much the same purpose as static variables in C.

With previous versions of Perl, to declare a persistent variable, we had to declare it outside the subroutine:

{
    my $count = 0;
    sub incrementCount {
        return $count ++;
    }
}

This construct is rather ugly, because the subroutine must be placed within a block itself. Using the new state keyword, we can rewrite the code above as:

sub incrementCount {
    state $count = 0;
    return $count ++;
}

Resources[edit]