Sharing

2013年5月27日 星期一

Perl 語言編程第四版筆記(一)

Chapter 3 Unary and Binary Operators


Binary x is the repetition operator.
In scalar context, it returns a concatenated string consisting of the left operand repeated the number of times specified by the right operand.

print "–" x 80;        # print row of dashes

In list context, if the left operand is a list in parentheses or is a list formed by qw/STRING/, the x works as a list replicator rather than a string replicator.

my @ones = (1) x 80;      # a list of 80 1's
@ones = (5) x @ones;      # set all elements to 5

my %hash;
my @keys = qw(perls before swine);
@hash{@keys} = ("") x @keys;



Smart Match


So ~~ is often best read aloud as “matches” or “matches any of”, because the left operand submits itself to be accepted or rejected by the right operand.

Left Right Description Like
Any undef Check whether Any is undefined !defined Any
Any ARRAY Smartmatch each ARRAY element grep { Any ~~ $_ } ARRAY
Any HASH HASH key existence exists HASH–>{Any}
Any Object Invoke ~~ overloading on Object, or die

Any CODE Sub passed Any returns true CODE–>(Any)
Any Regexp Pattern match Any =~ /Regexp/
Any Num Numeric equality Any == Num
Any Any String equality Any eq Any








undef ARRAY undef in ARRAY grep { !defined } ARRAY
undef HASH Always false (undef can’t be a key) 0 == 1








ARRAY1 ARRAY2 Recurse on paired elements of
ARRAY1 and ARRAY2
(ARRAY1[0] ~~ ARRAY2[0]) && (ARRAY1[1] ~~ ARRAY2[1]) && ...
ARRAY HASH Any ARRAY elements exist as HASH keys grep { exists HASH–>{$_} } ARRAY
ARRAY CODE Sub returns true on all ARRAY elements !grep { !CODE–>($_) } ARRAY
ARRAY Regexp Any ARRAY elements pattern match Regexp grep { /Regexp/ } ARRAY








HASH1 HASH2 All same keys in both HASH keys HASH1 == grep { exists HASH2–>{$_} } keys HASH1
HASH CODE Sub returns true on all HASH keys !grep { !CODE–>($_) } keys
HASH
HASH Regexp Any HASH keys pattern match Regexp grep { /Regexp/ } keys HASH








Num numlike Numeric equality num == numlike


Range Operators


my @alphabet = ("A" .. "Z");
my $hexdigit = (0 .. 9, "a" .. "f")[$num & 15]
my @z2 = ("01" .. "31");
print $z2[$mday];
my @combos = ("aa" .. "zz");
use charnames "greek";
my @greek_small = ("\N{alpha}" .. "\N{omega}");

Logical and, or, not, and xor


my $x,$y,$z,$xyz;

$x = 0;
$y = 1;
$z = 5;

$xyz = $x || $y || $z;  # output 1

$xyz = $x or $y or $z;  # wrong, it will execute "="  before "or",  output 0

$xyz = ( $x or $y or $z );  # correct, output 1


Chapter 4 Statements and Declarations


Compound Statements


if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ...
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

unless (EXPR) BLOCK
unless (EXPR) BLOCK else BLOCK
unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

given (EXPR) BLOCK

LABEL while (EXPR) BLOCK
LABEL while (EXPR) BLOCK continue BLOCK # for loop 的變形

LABEL until (EXPR) BLOCK
LABEL until (EXPR) BLOCK continue BLOCK

LABEL for (EXPR; EXPR; EXPR) BLOCK

LABEL foreach (LIST) BLOCK
LABEL foreach (LIST) BLOCK continue BLOCK
LABEL foreach VAR (LIST) BLOCK
LABEL foreach VAR (LIST) BLOCK continue BLOCK

LABEL BLOCK
LABEL BLOCK continue BLOCK

given statement


use feature ":5.10";
given ($n) {
    # match if !defined($n)
    when (undef) {
        say '$n is undefined';
    }

    # match if $n eq "foo"
    when ("foo") {
        say '$n is the string "foo"';
    }

    # match if $n ~~ [1,3,5,7,9]
    when ([1,3,5,7,9]) {
        say '$n is an odd digit';
        continue; # Fall through!!
    }

    # match if $n < 100
        when ($_ < 100) {
        say '$n is numerically less than 100';
    }

    # match if complicated_check($n)
    when (\&complicated_check) {
        say 'a complicated check for $n is true';
    }

    # match if no other cases match
    default {
        die q(I don't know what to do with $n);
    }
}

Loop>

The syntax for the loop-control operators is: last LABEL next LABEL redo LABEL goto LABEL A BLOCK by itself (labelled or not) is semantically equivalent to a loop that executes once. Thus, you can use last to leave the block or redo to restart the block. Note that this is not true of the blocks in eval {}, sub {}, or, much to everyone’s surprise, do {}. Loop controls don’t work in an if or unless, either, since those aren’t loops. But you can always introduce an extra set of braces to give yourself a bare block,
if (/pattern/) {{
    last if /alpha/;
    last if /beta/;
    last if /gamma/;
    # do something here only if still in if()
}}

The Ellipsis Statement

Perl accepts a bare ellipsis, “...” as a stub—that is, a place holder for code that you haven’t implemented yet.
sub unimplemented { ... }
eval { unimplemented() };
if ($@ =~ /Unimplemented/) {
    say "Caught an Unimplemented exception!";
}

Scope Declaration

Perl’s three scoping declarators make it easy to create completely private variables (using my or state), or to give selective access to global ones (using our). There is also a pseudodeclarator to provide temporary values to global variables (using local). These declarators are placed in front of the variable in question
my $nose;
our $House;
state $troopers = 0;
local $TV_channel;

Pragmas

use warnings;
# or explicitly enable warnings
...
{
no warnings;
# Disable warnings through end of block.
...
}
# Warnings are automatically enabled again here.

沒有留言: