偶尔翻翻书Perl,记录一些平时用的少的东西。
last update: 2014-12-10
wantarray(),函数返回上下文判断参考,Perldoc。
sub context_sensitive {
my $context = wantarray();
return qw( List context ) if $context;
say 'Void context' unless defined $context;
return 'Scalar context' unless $context;
}
use integer
临时变量通常情况下能提高性能
use Memoize – Make functions faster by trading space for time。也可自己用临时变量、甚至数据库存储。
print性能: print "$_\n" < print $_. "\n" < print $_, "\n"
Array slices: @cats[-1, -2]; @cats[0 .. 2];
Hash Slices
# %cats already contains elements
@cats{qw( Jack Brad Mars Grumpy )} = (1) x 4;
# equivalent to the initialization:
my %cats = map { $_ => 1 } qw( Jack Brad Mars Grumpy );
# Hash slices make it easy to merge two hashes:
my %addresses = ( ... );
my %canada_addresses = ( ... );
@addresses{ keys %canada_addresses } = values %canada_addresses;
Hash::Util can make hashes safer using lock.
while (<FILE>)
`用了缓存的
Filehandle References. Internally, these filehandles are objects of the class IO::File. You can call methods on them directly
``use autodie ‘open’; open my $out_fh, ‘>’, ‘output_file.txt’; $out_fh->say( ‘Have some text!’ );
use FileCache to open a lot of files
Catching Exceptions
local $@;
# log file may not open
my $fh = eval { open_log_file( 'monkeytown.log' ) };
# caught exception
if (my $exception = $@) {
die $exception unless $exception =~ /^Can't open logging/;
$fh = log_to_syslog();
}
Try::Tiny is easy to use:
use Try::Tiny;
my $fh = try { open_log_file( 'monkeytown.log' ) }
catch { log_exception( $_ ) };
Carp – alternative warn and die for modules
Regular expression
Perl Regex Detail from perldoc perlre.
(?<=pattern)abc # positive lookbehind
(?<!pattern)abc # negative lookbehind
abc(?=pattern) # positive lookahead
abc(?!pattern) # negative lookahead
The qr// Operator
my $hat = qr/hat/;
say 'Found a hat!' if $name =~ /$hat/;
Par::Packer 命令:
pp -f Bleach -o test.exe test.pl
所读书目: