2015年4月21日星期二
Perl : subroutine signatures 跟 prototypes
http://modernperlbooks.com/mt/2009/08/the-problem-with-prototypes.html
http://docstore.mik.ua/orelly/perl4/prog/ch06_04.htm
http://stackoverflow.com/questions/297034/why-are-perl-5s-function-prototypes-bad
subroutine signatures 跟其他函数没太大差别,就是函数变量声明一下,不合适的warning一下
prototype 则提供接近内置函数的功能,使用时不用带括号、自动识别上下文,例如
sub mypop (\@)
mypop @array
2013年7月8日星期一
perl 5.18改用siphash
见:
https://metacpan.org/module/RJBS/perl-5.18.0/pod/perldelta.pod
https://131002.net/siphash/
https://131002.net/siphash/siphash.pdf
2013年6月27日星期四
2013年2月27日星期三
Perl : 把quotemeta反过来,反转义
sub reverse_quotemeta {
my ($data) = @_;
my $string = '$data = "' . qq|$data| . '";';
eval $string;
return $data;
} ## end sub reverse_quotemeta
2013年1月30日星期三
MongoDB : mapreduce传参例子
// data : { cola : xxx , colb : yyy , colc : { colca : 1 , colcb : 2 } }
mr_main_func = function(mr){
mr["map"] = function(){
var raw = this.colc;
for(k in raw){
var emit_data = {
cola : this.cola,
colb : this.colb,
colc_field : k
};
emit(emit_data, 1);
}
};
mr["reduce"] = function(key, emits) {
total = 0;
for (var i in emits) {
total += emits[i];
}
return total;
};
mr["verbose"] = true;
db.runCommand(mr);
};
mr_main_func({
"mapreduce" : src,
"out" : { "reduce": dst }
});
2012年12月4日星期二
Perl : 用Mail::Sender发送邮件
use Mail::Sender;
sub send_mail {
# from,to,cc, subject, message, attach = [ ]
# smtp_server : xxx.xxx.xxx.xxx
# message_charset : default gbk
# ctype : default text/html
# auth : default LOGIN
my ($m) = @_;
$m->{message_charset} ||= 'gbk';
$m->{ctype} ||= 'text/html';
$m->{auth} ||= 'LOGIN';
#print "send_mail : $m->{subject}\nfrom:$m->{from}\nto:$m->{to}\ncc:$m->{cc}\n";
my $sender = new Mail::Sender {
smtp => $m->{smtp_server},
from => $m->{from},
#debug => '/tmp/mail_debug.txt',
boundary => '----this-is-a-mail-boundary-----',
};
die "Can't create the Mail::Sender object: $Mail::Sender::Error"
unless ref $sender;
$sender->OpenMultipart( {
to => $m->{to},
cc => $m->{cc},
replyto => $m->{from},
# fake_from => $m->{fake_from},
# auth => $m->{auth},
# authid => $m->{user},
# authpwd => $m->{passwd},
from => $m->{from},
ctype => $m->{ctype},
subject => $m->{subject},
} );
$sender->Body( {
charset => $m->{message_charset},
msg => $m->{message},
} );
for my $attach_file (@{$m->{attach}}) {
$sender->Attach( {
description => "$attach_file",
ctype => 'text/html',
disposition => "attachment;filename=$attach_file",
file => "$attach_file",
id => "$attach_file",
} )
|| die "Error in attachment: $Mail::Sender::Error\n"
if ( -f $attach_file );
} ## end for my $attach_file (@$attach_files_ref)
$sender->Close;
} ## end sub send_mail
2012年11月20日星期二
Perl : ip 与 inet 十进制字符串互转
use Socket;
my $ip = '202.38.75.11';
my $inet_str = unpack('N', inet_aton($ip));
my $ip_re = inet_ntoa(pack('N', $inet_str));
2012年11月7日星期三
Perl : 多进程连DBI的时候报错
两种方法:
1)不用DBI连:换成DBIx::Connector就可以了
2)panda找到的方法:用DBI连,InactiveDestroy属性设成1
2012年7月13日星期五
2012年5月19日星期六
Programming Perl 4th : Chapter 9 - Chapter 19
$SIG{QUIT} = *quit_catcher; # forces current package's sub
继承用parent了:
package Horse;
use parent qw(Critter);
可以把其他类的子函数借来用用,INVOCANT–>DOES(ROLE)
2012年4月22日星期日
Programming Perl 4th : Chapter 6 - Chapter 8
最烦的就是这种传参潜规则了
:&foo; # foo() gets current args, like foo(@_), but faster!
foo; # like foo() if sub foo predeclared, else bareword "foo"
state不能用于 %hash,但可用于 $hashref
函数属性有两种,lvalue和method,可以用 sub somefunction : method {} 声明
左值函数的返回值能够被直接被赋值
:my $val;
sub canmod : lvalue {
$val;
}
sub nomod {
$val;
}
canmod() = 5;
nomod() = 5;
# Assigns to $val.
# ERROR
软链接是解引用时用到的变量名称,可以用 use strict "refs"; 关闭
${identifier}; # Same as $identifier.
${"identifier"}; # Also $identifier, but a symbolic reference.
注意:软链接涉及symbol table,因此仅对包变量生效,对词法变量无效。
Tie::RefHash 支持将HASHREF做索引
2012年4月8日星期日
Programming Perl 4th : Chapter 5 正则
/r 保留原来变量的值不变,返回替换后的新值
$+{name} 保存命名正则(?<name>...)最近一次匹配的内容
@{ $-{name} } 保存命名正则(?<name>...)多次匹配的内容
假设 $pattern_str 是正则式匹配串:
- 如果在某个循环中, ... if(/$pattern_str/) 则每次调用都会重复编译成正则式
- 如果在进入循环之前,先 $pattern = qr/$pattern_str/,则 ... if(/$pattern/) 每次调用不会重复编译成正则式
use re 'debug'; 可以看正则式解析过程
NFA会记录上次匹配位置,失败后回溯,再到下一个位置重复尝试匹配
(?> PATTERN) 与 (?: PATTERN) 用法类似,但 (?> PATTERN) 只要能匹配上,不管后续整体正则式匹配是否成功,都不回溯。
好处在于失败时能够迅速跳出,不尝试多余都回溯;当然,(?> PATTERN) 的"失败"有可能是判断错误的。
例子: "aaab" =~ /(?:a*)ab/ 成功, "aaab" =~ /(?>a*)ab/ 失败
(?>.+) 可以缩写为 .++
s/(\d+)/$1 * 2/e; # Replaces "42" with "84"
s/PATTERN/CODE/ee 相当于 s/PATTERN/eval(CODE)/e
(?{ CODE }) 好麻烦,暂时跳过不看了,P299
(?(COND)IFTRUE|IFFALSE) 比较帅!
perl支持切换正则引擎,例如re::engine::RE2等。
RE2的相关资料:
- Regular Expression Matching Can Be Simple and Fast
- Regular Expression Matching: The Virtual Machine Approach
- Regular Expression Matching in the Wild
2012年3月31日星期六
Programming Perl 4th : Chapter 2 - Chapter 4
$x = ( ($a, $b) = (7,7,7) ); # set $x to 3, not 2
识别句法的原则是,尽量当成函数参数。如果想让perl尽量不当成函数参数,可以在前面加个+号。最终效果看优先级。
chdir +($foo) || die; # (chdir $foo) || die
chdir +($foo) * 20; # chdir ($foo * 20)
next unless –M $file > .5; # files are older than 12 hours,这个好用!
智能匹配是递归取到底的:
my @little = qw(red blue green);
my @bigger = ("red", "blue", [ "orange", "green" ] );
if (@little ~~ @bigger) { # true!
say "little is contained in bigger";
}
智能匹配检查HASH时只管看key,不管value
智能匹配先看右边的项,再看左边的项
given-when赋值要用do圈起来,因为given-when是返回状态,而非赋值:
my $value = do {
given (<STDIN>) {
0xFF0000 when /red/i;
0x00FF00 when /green/i;
0x0000FF when /blue/i;
warn "unknown RGB component '$_', using black instead\n";
0x000000;
}
};
given是生成一个词法作用域的$_,跟foreach里面用的全局$_作用域不同。
when的组合匹配太晕了,暂时不看了P181
eval/sub/do的代码块,不是循环,不能直接用last/redo啥的,do可以多套一副括号绕过限制。
do {{ last if ... }} while(...);
our限制变量可用范围,local限制某个变量某个取值的覆盖范围,my则是词法变量二者均限制。my/local声明变量而不显示赋值时,默认会设成undef/()。
our变量一经指定,则相当于覆盖该范围的全局变量,任何改动即时生效。
针对our变量加local声明赋新值,该新值不能穿透子函数内部生效。
2012年2月21日星期二
笔记:Programming Perl 4th Part 1
命名的正则匹配项:s/(?<alpha>\S+)\s+(?<beta>\S+)/$+{beta} $+{alpha}/
What You Don't Know Won't Hurt You (Much) 这句我喜欢,:),学海无涯,学无止境,不用过于在意某些方面的无知。
2012年1月10日星期二
笔记:关于构造冲突串使hash退化为链表
论文:CrosbyWallach_UsenixSec2003.pdf
先汗一个,这论文都整出来多少年了……
问题在于各基础语言用的是“伪HASH”,桶长较小,冲突串容易构造。
加随机数初始化,且限制提交字符的串长度缓解。
参考:2007_28C3_Effective_DoS_on_web_application_platforms.pdf
perl的fix说明:perlsec.html#Algorithmic-Complexity-Attacks
perl5.8.1之后,大体上是加个随机种子PERL_HASH_SEED,且运行时一些操作可以动态改变hash值在桶内的位置,增加构造冲突串的复杂度。
由于这个随机处理,两次执行相同脚本,相同hash打出来的key顺序也不同。并且每次插入hash值也会导致key顺序发生变动。perl并不保证hash的key顺序一直固定。
可以把PERL_HASH_SEED置0,则不做随机处理,用于一些特殊的函数,如List::Util::shuffle()。
2011年11月14日星期一
Perl : 10进制转换成16进制
#需求:将一个10进制的大数,用16进制分解成4份
#法1:类似C的写法
my $l = 281474983985353;
my $a = $l % 0x100000000;
my $b = ($l-$a)/0x100000000;
my $major = $b >> 16;
my $minor = $b % 0x10000;
my $build = $a >> 16;
my $ext = $a % 0x10000;
print "$major $minor $build $ext\n";
#法2:用Math::BigInt大数库
my $t = new Math::BigInt('281474983985353');
my @result;
while($t){
my ($t, $s) =$t->bdiv(0x10000);
unshift @result, s;
}
print join(" ", @result, "\n");
#法3:可以用pack,需要支持Q选项,与perl编译的版本有关
2011年7月11日星期一
笔记:Learning Perl 第6版
/a 表示匹配ascii字符
/u 表示匹配unicode字符
/l 表示匹配本地字符
命名匹配: (?<name>\w+)
在正则式中复用之前的命名匹配:\g{name} 或 \k<name>
匹配完取内容:$+{name}
相对于given-when的默认smart match,也可以用以前正则匹配的dump match
在when的代码块末尾加continue,就会继续往下匹配,而不是默认的有个匹配后跳出given-when检查
获取外部命令输出的模块 IPC::System::Simple
执行指令挂掉检查,autodie配合Try::Tiny来用
每次取三个元素出来处理:
附录有介绍unicode
2010年12月20日星期一
2010年12月6日星期一
笔记 : Automating System Perl
tcpvcon -anc
有个用IO::Socket发DNS请求和解析DNS应答的例子
lstat与stat的差别:
stat返回symbolic link本身的信息,stat返回symbolic link指向的目标文件信息
笔记 : Perl DBI
Storable模块:nfreeze比freeze慢,但是保证可跨系统使用
Fcntl的flock
DB_FILE可以有三种存储形式 HASH、B树、RECNO(文本)
MLDBM 支持将复杂的数据结构写入文件
DBI的PrinterError对应warn,RaiseError对应die
错误消息:$DBI::errstr
quote函数自动转义引号
trace函数指定输出DB操作详情,debug用
dump_results打印执行结果,指定写入文件
bind_param_inout指定输出的参数写入到什么变量
bind_col
$sth->{NUM_OF_FIELDS}返回的列数
$sth->{NAME}->[$i-1] 第i列的名字
AutoCommit如果设为0,在执行一系列操作后,$dbh->commit(); if($@) { $dbh->rollback(); },较稳妥。
ODBC标准化了错误码,支持更多函数操作
DBI PROXY : 转发client的query给db,把db返回的结果转给client,这样中转一下,unix机器就能访问windows access的数据库