25. switch
given ($foo) {
when (1) { say "$foo == 1" }
when ([2,3]) {
say "$foo == 2 || $foo == 3"
}
when (/^a[bc]d$/) {
say "$foo eq 'abd' || $foo eq 'acd'"
}
when ($_ > 100) { say "$foo > 100" }
default { say "None of the above" }
}
26. state variables
sub counter {
state $counts = 0;
$counts += 1;
}
58. package Point;
use Moose;
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
81. sub AUTOLOAD {
my $program = $AUTOLOAD;
$program =~ s/.*:://;
system($program, @_);
}
date();
who('am', 'i');
ls('−l');
82. Android.pm
sub AUTOLOAD {
my ($method) = ($AUTOLOAD =~ /::(w+)$/);
return if $method eq 'DESTROY';
# print STDERR "$0: installing proxy method '$method'n";
my $rpc = rpc_maker($method);
{
# Install the RPC proxy method, we will not came here
# any more for the same method name.
no strict 'refs';
*$method = $rpc;
}
goto &$rpc; # Call the RPC now.
}
89. # from self.pm
sub _args {
my $level = 2;
my @c = ();
package DB;
@c = caller($level++)
while !defined($c[3]) || $c[3] eq '(eval)';
return @DB::args;
}
sub self { (_args)[0] }
90. # from self.pm
sub _args {
my $level = 2;
my @c = ();
package DB;
@c = caller($level++)
while !defined($c[3]) || $c[3] eq '(eval)';
return @DB::args;
}
sub self { (_args)[0] }
91. Furthermore, when called from within the DB package, caller
returns more detailed information: it sets the list variable
@DB::args to be the arguments with which the subroutine was
invoked.
# from self.pm – perldoc caller
sub _args {
my $level = 2;
my @c = ();
package DB;
@c = caller($level++)
while !defined($c[3]) || $c[3] eq '(eval)';
return @DB::args;
}
sub self { (_args)[0] }
99. How it works
• you define “declarator” keywords
• it let compiler stop at the keywords
• your code parse the current line in your way,
maybe re-write it
• you replace current line with the new one
• resumes the compiler on the current line