Perl Note

· Read in about 2 min · (315 Words)

偶尔翻翻书Perl,记录一些平时用的少的东西。

last update: 2014-12-10

语法

perl中my与local的区别 

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 { $_ =&gt; 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.

Regex look-around:中文英文

(?<=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

所读书目: