Mais conteúdo relacionado Semelhante a Perl Bag of Tricks - Baltimore Perl mongers (20) Perl Bag of Tricks - Baltimore Perl mongers1. My Perl
Bag of Tricks
brian d foy
The Perl Review
Baltimore Perl mongers
3. % perl -e "print qq(Hello Worldn)"
!
% perl -le "print q(Hello World)"
4. my $string = some_sub();
!
open my $fh, '<', $string;
!
while(<$fh>){
chomp;
...;
}
5. use 5.014;
!
my $new = $old =~ s/.../.../r;
!
foo( $old =~ s/.../.../r );
!
print "%s %sn",
$old,
$old =~ s/.../.../r
;
6. foreach my $file ( @files ) {
open my($fh), '>', $file or do {
warn "... $!n";
next FILE;
};
...
}
7. my $data = do {
local $/; <DATA>
};
...;
!
__END__
<?xml version="1.0"?>
<root>
...
</root>
8. my $data = do { local $/; <DATA> };
!
s|.*(?=<elem>)||; s|(?<=</elem>).*||;
!
my $name =
m|<elem>(.*?)</elem>|;
!
__END__
<?xml version="1.0"?>
<root>
...<elem>Buster</elem>
</root>
10. $g =
q("Roscoe "","" Cat","Bean, Buster");
!
my @gatos =
split
/(?<!"")(?<="),(?=")(?!"")/, $g;
11. if( ref $r eq 'ARRAY' )
!
if( ref $r eq ref [] )
!
if( ref $r eq ref {} )
!
if( ref $r eq ref sub {} )
!
if( ref $r eq ref qr// )
13. BEGIN {
use Foo;
package Foo;
no warnings qw(redefine);
sub foo { ... }
}
14. # Git::CPAN::Patch
!
% git cpan-init http://...
... hack hack hack ...
% git commit
% git cpan-sendpatch
15. my $file = MPEG::Info->new( ... );
!
print
join $/,
map {
$file->$_()
} qw(acodec
acodecraw
achans
...
);
17. if( /p{IsUppercaseRoman}/ ) {
...}
!
# Ⅰ Ⅴ Ⅹ Ⅼ Ⅽ Ⅾ Ⅿ ↁ ↂ ↇ ↈ
sub IsUppercaseRoman {
return <<"CODE_NUMBERS";
2160
2164
2169
216C 216F
2181 2182
2187 2188
CODE_NUMBERS
}
19. gato( name => 'Buster' );
!
sub gato {
my %defaults = (...);
my %config = (%defaults, @_ );
...;
}
20. 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 );
21. sub my_grep (&@) {
my( $sub ) = shift;
foreach my $arg ( @_ ) {
local $_ = $arg;
push @output, $arg
if $sub->()
}
}
23. sub composer {
my (@sub_refs) = @_;
sub {
my $string = shift;
foreach my $sub_ref (@sub_refs) {
$string = $sub_ref->($string);
}
return $string;
};
}
24. 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]
);
}
25. 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;
}
...;
}
26. $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 }
}