This document summarizes Brian D Foy's presentation on "My Perl Bag of Tricks" given at YAPC::Brasil 2011. Some of the tricks discussed include eliminating special cases, using Perl to do more of the work, scaling code gracefully, parsing XML data efficiently, testing code with sample inputs/outputs, and handling errors gracefully. The presentation aims to show Perl techniques for writing cleaner, more robust code.
23. gato( nome => 'Buster' );
sub gato {
my %defaults = (...);
my %config = (%defaults, @_ );
...;
}
24. BEGIN {
my $fixed_time = 1234567890;
no warnings qw(redefine);
*CORE::GLOBAL::time =
sub { $fixed_time };
sub set_time {
$fixed_time = $_[0]
}
}
ok( time > $fixed_time );
25. sub my_grep (&@) {
my( $sub ) = shift;
foreach my $arg ( @_ ) {
local $_ = $arg;
push @output, $arg
if $sub->()
}
}
27. sub composer {
my (@sub_refs) = @_;
sub {
my $string = shift;
foreach my $sub_ref (@sub_refs) {
$string = $sub_ref->($string);
}
return $string;
};
}
28. my @tests = (
# ARG EXPECTED LABEL
[ [1,2,3], 6, 'Sum is 6' ],
[ [-1,0,9], 8, 'Sum is 8' ],
...
);
foreach my $test ( @tests ) {
is(
target_sub( $test->[ARG] ),
$test->[EXPECTED],
$test->[LABEL]
);
}
29. package Local::Null::Logger {
sub new { bless my $x, $_[0] }
sub AUTOLOAD { shift; print @_, $/ }
sub DESTROY { 1 }
}
sub _init_logger {
my $log4perl_loaded =
eval "require Log::Log4perl; 1";
unless( $log4perl_loaded ){
return Local::Null::Logger->new;
}
...;
}
30. $object->foo->bar->baz->quux;
package Class {
sub bar {
return Null->new if $error;
}
}
package Null {
my $null = bless {}, __PACKAGE__;
sub new { $null }
sub AUTOLOAD { return $_[0] }
sub DESTROY { 1 }
}