Chapter 15: Smart Matching and given-when-Smart Match Precedence
~~智能匹配符
左右两边变量的次序可以对调。
可以智能匹配:
%a ~~ %b 两个Hash的key是否全部相同
%a ~~ @b 至少有一个%a的key在@b中出现
%a ~~ /Fred/ 至少有一个%a的key能匹配指定的模式
%a ~~ 'Fred' 存在$a{'Fred'}项
@a ~~ @b 两个Array是否完全相同
@a ~~ /Fred/ 至少有一个$a[i]匹配模式
@a ~~ 123 至少有一个$a[i]==123
@a ~~ 'Fred' 至少有一个$a[i] eq 'Fred'
如果在左右两边都是标量的情况下,此时Perl需要根据两边的取值来决定比较的方式(字符串?数值?等等)。
Chapter 15: Smart Matching and given-when-The given Statement
given-when类似C中的switch-case,只是given-when默认是break,除非在结尾显式指定continue才会接着往下跑。
foreach-when则是对指定Array中的所有元素都搞一遍given-when。
如果要用智能匹配,那么foreach-when里面的循环量就要指定为$_。
Chapter 16: Process Management
system是另外建立一个子进程执行指令,而Perl进程停下来等它结束之后再继续往后执行。
exec是Perl进程自己跑去执行指令,成功执行完毕后Perl进程自己也退出了。
fork子进程的时候可能用到exec,一般情况下都用system。
想得到指令输出内容才跑去用反引号执行指令,比如`ls -l`。
如果只是想执行指令,而不管输出内容,用system就好。
还有进程间通信以及信号的内容,写得很赞。
open DATE, "date|" or die "cannot pipe from date: $!";读入date指令的输出内容进行处理。 open MAIL, "|mail merlyn" or die "cannot pipe to mail: $!";将输入的内容传递给mail指令处理。
IPC::Open3控制进程的读、写、错误流。
$SIG{'INT'}= \&some_func;设定CTRL-C中断程序时进行的处理操作。
Chapter 16: Process Management-Exercises 2
用IPC::Open3控制正常输出及错误输出流
Modify the previous program to send the output of the command to a file called ls.out in the current directory. The error output should go to a file called ls.err. (You don't need to do anything special about the fact that either of these files may end up being empty.)
书后的参考答案是这样的:
open STDOUT, ">ls.out" or die "Can't write to ls.out: $!"; open STDERR, ">ls.err" or die "Can't write to ls.err: $!"; chdir "/" or die "Can't chdir to root directory: $!"; exec "ls", "-l" or die "Can't exec ls: $!";
又去找了点重定向的东西:
#!/usr/bin/perl use IO::File; use IPC::Open3; use Symbol qw(gensym); my $cmd = "ls -l /"; local *GETERR = ( new IO::File '> cmd.err' or die ); my $pid = open3( gensym, my $output , ">&GETERR", $cmd); while( my $out = <$output> ) { print $out."\n"; } waitpid( $pid, 0 ) or die; $? and die;
也就是,指令正常执行,则用print $out输出到STDOUT;否则,将错误信息重定向到cmd.err文件。
APPENDIX B-Beyond the Llama
use Fatal qw/ open chdir /;
省掉
chdir '/home/merlyn' or die "some error!";
后面的or die "some error!"
Text::Wrap
设定文本段落样式。
find2perl
将find指令转成对应的perl代码,通过-eval参数指定对每个找到的文件的操作。
没有评论:
发表评论