Perl语言入门 /** * prism.js Github theme based on GitHub's theme. * @author Sam Clarke */ code[class*="language-"], pre[class*="language-"] { color: #333; background: none; font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; text-align: left; white-space: pre; word-spacing: normal; word-break: normal; word-wrap: normal; line-height: 1.4; -moz-tab-size: 8; -o-tab-size: 8; tab-size: 8; -webkit-hyphens: none; -moz-hyphens: none; -ms-hyphens: none; hyphens: none; } /* Code blocks */ pre[class*="language-"] { padding: .8em; overflow: auto; /* border: 1px solid #ddd; */ border-radius: 3px; /* background: #fff; */ background: #f5f5f5; } /* Inline code */ :not(pre) > code[class*="language-"] { padding: .1em; border-radius: .3em; white-space: normal; background: #f5f5f5; } .token.comment, .token.blockquote { color: #969896; } .token.cdata { color: #183691; } .token.doctype, .token.punctuation, .token.variable, .token.macro.property { color: #333; } .token.operator, .token.important, .token.keyword, .token.rule, .token.builtin { color: #a71d5d; } .token.string, .token.url, .token.regex, .token.attr-value { color: #183691; } .token.property, .token.number, .token.boolean, .token.entity, .token.atrule, .token.constant, .token.symbol, .token.command, .token.code { color: #0086b3; } .token.tag, .token.selector, .token.prolog { color: #63a35c; } .token.function, .token.namespace, .token.pseudo-element, .token.class, .token.class-name, .token.pseudo-class, .token.id, .token.url-reference .token.variable, .token.attr-name { color: #795da3; } .token.entity { cursor: help; } .token.title, .token.title .token.punctuation { font-weight: bold; color: #1d3e81; } .token.list { color: #ed6a43; } .token.inserted { background-color: #eaffea; color: #55a532; } .token.deleted { background-color: #ffecec; color: #bd2c00; } .token.bold { font-weight: bold; } .token.italic { font-style: italic; } /* JSON */ .language-json .token.property { color: #183691; } .language-markup .token.tag .token.punctuation { color: #333; } /* CSS */ code.language-css, .language-css .token.function { color: #0086b3; } /* YAML */ .language-yaml .token.atrule { color: #63a35c; } code.language-yaml { color: #183691; } /* Ruby */ .language-ruby .token.function { color: #333; } /* Markdown */ .language-markdown .token.url { color: #795da3; } /* Makefile */ .language-makefile .token.symbol { color: #795da3; } .language-makefile .token.variable { color: #183691; } .language-makefile .token.builtin { color: #0086b3; } /* Bash */ .language-bash .token.keyword { color: #0086b3; } /* highlight */ pre[data-line] { position: relative; padding: 1em 0 1em 3em; } pre[data-line] .line-highlight-wrapper { position: absolute; top: 0; left: 0; background-color: transparent; display: block; width: 100%; } pre[data-line] .line-highlight { position: absolute; left: 0; right: 0; padding: inherit 0; margin-top: 1em; background: hsla(24, 20%, 50%,.08); background: linear-gradient(to right, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0)); pointer-events: none; line-height: inherit; white-space: pre; } pre[data-line] .line-highlight:before, pre[data-line] .line-highlight[data-end]:after { content: attr(data-start); position: absolute; top: .4em; left: .6em; min-width: 1em; padding: 0 .5em; background-color: hsla(24, 20%, 50%,.4); color: hsl(24, 20%, 95%); font: bold 65%/1.5 sans-serif; text-align: center; vertical-align: .3em; border-radius: 999px; text-shadow: none; box-shadow: 0 1px white; } pre[data-line] .line-highlight[data-end]:after { content: attr(data-end); top: auto; bottom: .4em; }html body{font-family:"Helvetica Neue",Helvetica,"Segoe UI",Arial,freesans,sans-serif;font-size:16px;line-height:1.6;color:#333;background-color:#fff;overflow:initial;box-sizing:border-box;word-wrap:break-word}html body>:first-child{margin-top:0}html body h1,html body h2,html body h3,html body h4,html body h5,html body h6{line-height:1.2;margin-top:1em;margin-bottom:16px;color:#000}html body h1{font-size:2.25em;font-weight:300;padding-bottom:.3em}html body h2{font-size:1.75em;font-weight:400;padding-bottom:.3em}html body h3{font-size:1.5em;font-weight:500}html body h4{font-size:1.25em;font-weight:600}html body h5{font-size:1.1em;font-weight:600}html body h6{font-size:1em;font-weight:600}html body h1,html body h2,html body h3,html body h4,html body h5{font-weight:600}html body h5{font-size:1em}html body h6{color:#5c5c5c}html body strong{color:#000}html body del{color:#5c5c5c}html body a:not([href]){color:inherit;text-decoration:none}html body a{color:#08c;text-decoration:none}html body a:hover{color:#00a3f5;text-decoration:none}html body img{max-width:100%}html body>p{margin-top:0;margin-bottom:16px;word-wrap:break-word}html body>ul,html body>ol{margin-bottom:16px}html body ul,html body ol{padding-left:2em}html body ul.no-list,html body ol.no-list{padding:0;list-style-type:none}html body ul ul,html body ul ol,html body ol ol,html body ol ul{margin-top:0;margin-bottom:0}html body li{margin-bottom:0}html body li.task-list-item{list-style:none}html body li>p{margin-top:0;margin-bottom:0}html body .task-list-item-checkbox{margin:0 .2em .25em -1.8em;vertical-align:middle}html body .task-list-item-checkbox:hover{cursor:pointer}html body blockquote{margin:16px 0;font-size:inherit;padding:0 15px;color:#5c5c5c;background-color:#f0f0f0;border-left:4px solid #d6d6d6}html body blockquote>:first-child{margin-top:0}html body blockquote>:last-child{margin-bottom:0}html body hr{height:4px;margin:32px 0;background-color:#d6d6d6;border:0 none}html body table{margin:10px 0 15px 0;border-collapse:collapse;border-spacing:0;display:block;width:100%;overflow:auto;word-break:normal;word-break:keep-all}html body table th{font-weight:bold;color:#000}html body table td,html body table th{border:1px solid #d6d6d6;padding:6px 13px}html body dl{padding:0}html body dl dt{padding:0;margin-top:16px;font-size:1em;font-style:italic;font-weight:bold}html body dl dd{padding:0 16px;margin-bottom:16px}html body code{font-family:Menlo,Monaco,Consolas,'Courier New',monospace;font-size:.85em !important;color:#000;background-color:#f0f0f0;border-radius:3px;padding:.2em 0}html body code::before,html body code::after{letter-spacing:-0.2em;content:"\00a0"}html body pre>code{padding:0;margin:0;font-size:.85em !important;word-break:normal;white-space:pre;background:transparent;border:0}html body .highlight{margin-bottom:16px}html body .highlight pre,html body pre{padding:1em;overflow:auto;font-size:.85em !important;line-height:1.45;border:#d6d6d6;border-radius:3px}html body .highlight pre{margin-bottom:0;word-break:normal}html body pre code,html body pre tt{display:inline;max-width:initial;padding:0;margin:0;overflow:initial;line-height:inherit;word-wrap:normal;background-color:transparent;border:0}html body pre code:before,html body pre tt:before,html body pre code:after,html body pre tt:after{content:normal}html body p,html body blockquote,html body ul,html body ol,html body dl,html body pre{margin-top:0;margin-bottom:16px}html body kbd{color:#000;border:1px solid #d6d6d6;border-bottom:2px solid #c7c7c7;padding:2px 4px;background-color:#f0f0f0;border-radius:3px}@media print{html body{background-color:#fff}html body h1,html body h2,html body h3,html body h4,html body h5,html body h6{color:#000;page-break-after:avoid}html body blockquote{color:#5c5c5c}html body pre{page-break-inside:avoid}html body table{display:table}html body img{display:block;max-width:100%;max-height:100%}html body pre,html body code{word-wrap:break-word;white-space:pre}}.markdown-preview{width:100%;height:100%;box-sizing:border-box}.markdown-preview .pagebreak,.markdown-preview .newpage{page-break-before:always}.markdown-preview pre.line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}.markdown-preview pre.line-numbers>code{position:relative}.markdown-preview pre.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:1em;font-size:100%;left:0;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.markdown-preview pre.line-numbers .line-numbers-rows>span{pointer-events:none;display:block;counter-increment:linenumber}.markdown-preview pre.line-numbers .line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}.markdown-preview .mathjax-exps .MathJax_Display{text-align:center !important}.markdown-preview:not([for="preview"]) .code-chunk .btn-group{display:none}.markdown-preview:not([for="preview"]) .code-chunk .status{display:none}.markdown-preview:not([for="preview"]) .code-chunk .output-div{margin-bottom:16px}.scrollbar-style::-webkit-scrollbar{width:8px}.scrollbar-style::-webkit-scrollbar-track{border-radius:10px;background-color:transparent}.scrollbar-style::-webkit-scrollbar-thumb{border-radius:5px;background-color:rgba(150,150,150,0.66);border:4px solid rgba(150,150,150,0.66);background-clip:content-box}html body[for="html-export"]:not([data-presentation-mode]){position:relative;width:100%;height:100%;top:0;left:0;margin:0;padding:0;overflow:auto}html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview{position:relative;top:0}@media screen and (min-width:914px){html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview{padding:2em calc(50% - 457px + 2em)}}@media screen and (max-width:914px){html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview{padding:2em}}@media screen and (max-width:450px){html body[for="html-export"]:not([data-presentation-mode]) .markdown-preview{font-size:14px !important;padding:1em}}@media print{html body[for="html-export"]:not([data-presentation-mode]) #sidebar-toc-btn{display:none}}html body[for="html-export"]:not([data-presentation-mode]) #sidebar-toc-btn{position:fixed;bottom:8px;left:8px;font-size:28px;cursor:pointer;color:inherit;z-index:99;width:32px;text-align:center;opacity:.4}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] #sidebar-toc-btn{opacity:1}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc{position:fixed;top:0;left:0;width:300px;height:100%;padding:32px 0 48px 0;font-size:14px;box-shadow:0 0 4px rgba(150,150,150,0.33);box-sizing:border-box;overflow:auto;background-color:inherit}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar{width:8px}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar-track{border-radius:10px;background-color:transparent}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar-thumb{border-radius:5px;background-color:rgba(150,150,150,0.66);border:4px solid rgba(150,150,150,0.66);background-clip:content-box}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc a{text-decoration:none}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc ul{padding:0 1.6em;margin-top:.8em}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc li{margin-bottom:.8em}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc ul{list-style-type:none}html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{left:300px;width:calc(100% - 300px);padding:2em calc(50% - 457px - 150px);margin:0;box-sizing:border-box}@media screen and (max-width:1274px){html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{padding:2em}}@media screen and (max-width:450px){html body[for="html-export"]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{width:100%}}html body[for="html-export"]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .markdown-preview{left:50%;transform:translateX(-50%)}html body[for="html-export"]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .md-sidebar-toc{display:none} /* Please visit the URL below for more information: */ /* https://shd101wyy.github.io/markdown-preview-enhanced/#/customize-css */
h1 { text-align: center } h2 { text-align: center }
作者:王鸿奇 邮箱:yilupiaoxuewhq@163.com
% cpan install App::cpanminus% cpanminus --uninstall Module::Name关于学习编程语言,再次我将提几个建议:
具体查看perlvar文档
变量 | 描述 |
|---|---|
$! | 可读的系统错误信息 |
$#array | 数组长度 |
$_ | 默认变量 |
$^R | 内嵌代码的运行结果 |
$" | 字符串中的数组内插的分隔符,默认为空格 |
$ARGV | 当前蒸菜处理的文件 |
@ARGV | 可执行程序的参数列表 |
$$ | 进程标识 |
$? | 进程结束时的返回值 |
%SIG | 信号处理函数,key是信号名(非前缀,如INT),value是信号处理函数 |
$@ | eval的返回值 |
$0 | 子程序名 |
$| | 缓冲设置 |
%ENV | 环境变量 |
$^I | 备份<>操作符操作的文件,该文件的后缀为$^I的值(默认不备份) |
$` | 正则匹配区段前的内容 |
$& | 正则匹配区段的内容 |
$' | 正则匹配区段后的内容 |
$^N, $+ | 编号最小和最大的捕获内容 |
%+ | 命名捕获组 |
@_ | 子程序的参数列表 |
61_284_042_283_586
2**3use utf8;
"hello" . "world""ha" x 2% perl -w my_programuse warnings;#! /usr/bin/perl -wuse diagnostics;% perl -W my_program+=,.=,/=,*=,**=等等
chr():代码转字符,$alef = chr( 0x05D0 )ord():字符转代码点,$code_point = ord('?')0,'','0',undef<STDIN>,读取的数据会带有换行符
chomp($text = <STDIN>)
0,字符串使用时如同''。
$"的值指定的,默认为空格
@rocks = qw( 1 2 3 );
$elem = pop @rocks; # @rocks: 1 2, $elem: 3
push @rocks $elem; # @rocks: 1 2 3@rocks = qw( 1 2 3 );
$elem = shift @rocks; # $elem: 1, @rocks: 2 3
unshift @rocks $elem; # @rocks: 1 2 3# format: @delete splice @dst, 位置, 删除个数, 插入元素
# 在原来的数组中删掉fred及其后元素
# @removed 编程 qw( fred barney betty )
# 而原先的@array则编程qw( pebbles dino )
@array = qw( pebbles dino fred barney betty);
@removed = splice @array, 2;
# 删除dino和fred这两个元素
# @removed 编程 qw( dino fred )
# 而 @array 则编程 qw( prebbles barney betty )
@array = qw( pebbles dino fred barney betty );
@removed = splice @array, 1, 2;
# 删除 dino 和 fred 并插入 wilma
# @removed 变成 qw( dino fred )
# @array 变成 qw( prebblees wilma barney betty )
@array = qw( pebbles dino fred barney betty );
@removed = splice @array, 1, 2 qw( wilma );# format: foreach 控制变量 (迭代器)
foreach $line (@text)
{
...
}sub func_name {...}&符号来调用:&func_name
&符号来调用:
sub func_name { return 0; } func_name&符号来调用:func_name( @args )
注意:建议只有在调用内置的时候省略&符号,其余的都加上&符号来区分调用的是内置还是自定义子程序。
return undef;return ();use feature state; state $first;
@_
use strict;
while/foreach循环的条件表达式中只有行输入操作符的前提下,这个简写才起作用:
while (<STDIN>) {...}while与foreach的区别:在while循环里,Perl会读取一行输入,把他存入某个变量并执行循环的主体,接下来它会回头去寻找其他的输入行。但是在foreach循环里,行输入操作符会在列表上下文中执行(因为foreach需要逐项处理列表内容,因此会一次性读取所有输入)
-:表示要从标准输入读取数据,在没有指定参数的时候,默认为连字符。open CONFIG, '<:encoding(UTF-8)', 'dino';% perl -Mencode -le "print for Encode->encodings(':all')";open BEDROCK, '>:crlf', $file_name;undef
$!:可读的系统错误信息
use autodie;
STDOUT:select LOG;$| = 1;
STDIN,STDOUT,STDERR时,Perl会恢复其默认的文件句柄。但其那题是,$^F没有被修改的情况下。
use feature say;打开此函数。
@any_array = %some_hash;
my %new_hash = %old_hash:
%old_hash展开为key-value列表,然后通过列表赋值重新构造每个key-value,最终形成新的hash%new_hash=>):胖箭头与逗号等效,所有右称为胖逗号
my %last_name = ( # hash也可以是词法变量 'fred' => 'flintstone', 'dino' => undef, 'barney'=> 'rubble', 'betty' => 'rubble', ); # 使用胖箭头的时候可以省略引号,左边的部分会自动被引起 my %last_name = ( fred => 'flintstone', dino => undef, barney => 'rubble', betty => 'rubble', );
(key, value)
\p{PROPERTY}:匹配PROPERTY属性\P{PROPERTY}:匹配非PROPERTY属性{M,N}:匹配至少M次,最多N次。{M,}:匹配至少M次{M}:匹配M次*:等同于{0,N},此处N意味着无上限+:等同于{1,N},此处N意味着无上限?:等同于{0,1}():捕获组,默认由序号表明。对应的序号可通过依次点算左括号(包括嵌套括号)的序号。\N:反向引用,N为正整数\g{N}:反向引用 N可以是负数,意味着相对于自己的位置,即往前第几个括号。N可以是名字$N:使用捕获组匹配的内容,N为正整数。|/fred|barney|betty/ # 可以匹配任何含有fred或者barney或者betty的字符串。[abc]:匹配字符,且该字符是'a'或'b'或'c'[a-z]:匹配字符,且该字符落在'a'到'z'之间[^ab]:匹配字符,且该字符即不是'a'也不是'b'[-ab]:匹配字符,且该字符是'-'或'a'或'b'[\000-\177]:匹配任意一个7位的ASCII字符(0 ~ 127)[\w]:ASCII的话即等效为:[-a-zA-Z0-9]\w\d\s:匹配任意空白。perl15.6之前,\s只能匹配[\f\t\n\r],可以通过/\s/a来按老的ASCII字符语义解释\h:水平空白\v:垂直空白\p{Space}:匹配任意空白,等效于[\h\v],等效于\s\R:匹配断行\W\D\SP{...}.: \n外。\s则可以匹配\nm即Match,后面跟着即为分隔符
m/pattern/modifier
m#pattern#modifier
m!pattern!modifier
m{pattern}modifier
m<pattern>modifier如果使用/作为分隔线,那么m可以省略。
列表上下文:返回所有捕获变量的列表,如果匹配失败则返回空列表
通过g全局匹配来返回多个捕获内容
my $text = "Fred dropped a 5 ton granite block on Mr.Slate";
my @words = ($text =~ /([a-z]+)/ig);
print "Result: @words\n";通过g全局匹配来讲捕获的字符串变成hash(列表转hash)
my $data = "Barney Rubble Fred Flintstone Wilma Flintstone";
my %last_name = ($data =~ /(\w+)\s+(\w+)/g);i:忽略大小写s:单行模式,可以匹配换行符m:多行模式,^和$变为匹配行开头和行结尾x:忽略空白符和注释,即要匹配空白符和#需要转义a:ascii模式l:类似于a,只是此时取决于本地化设定u:Unicode模式\A:匹配字符串的绝对开头\z:匹配字符串你的绝对末尾\Z:匹配行尾,即\n前^:匹配字符串的绝对开头,等效于\A,当使用m时,匹配行开头$:匹配字符串的绝对末尾,等效于\z。当使用m时,匹配行末尾\b:单词边界,即一组连续的\w字符开头或结尾\G:上次匹配结束的位置%+(?:...)(?<LABEL>...)\g{LABEL}\k<LABEL>$`$&$'(...),(?:...),(?<LABEL>...)*,+,?,{n,m}abc,^,$,\A,\b,\z,\Z|a, [...],\d,\1,\g{LABEL}s{fred}{barney};s[fred](barney);s<fred>#barney#;g:全局替换r:使返回值编程替换后的结果,而保留变量中的原字符串?来启用非贪婪模式(匹配尽可能少的字符)读取UTF-8文档:use open OUT => ':encoding(UTF-8)';
命令行直接运行:查看perlrun文档
% perl -p -i.bak -w -e 's/Randall/Randal/g' fred*.dat-P:可以让Perl自动生成一端小程序,类似:
while (<>) { print; }-n:抹掉-P中自动执行的print
-i.bak:把$^I设置为".bak",如果你不想做备份的话,请直接写出-i
-e:后跟可供执行的程序
$n = 1 if ! defined $n # 此写法两边仅能是单个表达式$n = 1 unless $n; # 此写法两边仅能是单个表达式until {$j > $i)}
{
$j *= 2;
}# is a foreach
for (1..10)
{
print "I can cut to $_!\n";
}last LABEL:就像C语言中的break,作用于for, foreach, while, until及裸块
next LABEL:就像C语言中的continue,作用于for, foreach, while, until及裸块
redo LABEL:将控制返回到当前循环体的顶端,而不经过任何测试条件,也不会进入下一次循环
continue:在when中使用,继续检查向下执行
\w组成,但不能以数字开头。LINE:while(<>) { foreach (split) { last LINE if /__END__/; # 如果发现有'__END__'的标记,则跳出至标签为LINE的循环 } }
//
cpan工具% perldoc CGI :查看CGI模块文档% cpan -a:查看已安装的模块ExtUtils::MakeMaker % perl Makefile.PL% make install % perl Makefile.PL INSTALL_BASE=/Users/fred/libModule::Build % perl Build.PL% ./Build install % perl Build.PL --install_base=/Users/fred/lib% perl -MCPAN -e shellcpan安装(推荐,简单方便) % cpan Module::CoreListcpanm% perl -Mlocal::lib
export PERL_LOCAL_LIB_ROOT='/Users/fred/perl5'; export PERL_MB_OPT='--install_base /Users/fred/perl5'; export PERL_MM_OPT='INSTALL_BASE=/Users/fred/perl5'; export PERL5LIB='/path/to/perl5lib'; export PATH='/Users/fred/perl5/bin:$PATH";% cpan -I Set::Crossproduct
local::lib的话,则在Perl程序内部加入代码use local::lib;use lib qw( /Users/fred/perl5 );use File::Basename;
use File::Basename qw/ basename /;
use File::Basename;
print 'please enter a filename: ';
chomp(my $old_name = <STDIN>);
my $dirname = dirname $old_name;
my $basename = basename $old_name;
$basename =~ s/^/not/; # 增加前缀
my $new_name = "$dirname/$basename";
rename $old_name, $new_name
or warn "Can't rename '$old_name' to '$new_name': $!";
print "$old_name, $new_name\n";use File::Basename;
use File::Spec;
print "Please enter a filename: ";
chomp(my $old_name = <STDIN>);
my $dirname = dirname $old_name;
my $basename = basename $old_name;
print "$old_name, $base_name\n";
my $new_name = File::Spec->cattle($dirname, $basename); # 将依据系统去拼接路径,比如WIN7用'\',Linux用'/'
rename $old_name, $new_name
or warn " Can't rename '$old_name' to '$new_name': $!";
print "$old_name, $new_name\n";my $dir = dir( qw(Users fred lib) ); # Users/fred/lib/perl5
my $subdir = $dir->subdir( 'perl5' );
my $parent = $dir->parent; # Users/fred
my $windir = $dir->as_foreign( 'Win32' ); # Users\fred\libuse CGI qw/ :all /; # 加载分组all,模块可以有不同的分组,比如::cgi,:html5
print header(),
start_html('This is the page title');
h1('Input parameters');
my $list_items;
foreach my $param ( param() )
{
$list_items .= li( "$param: " . param($param) );
}
print ul( $list_items );
print end_html();use time::Piece;
my $t = localtime;
print 'The month is ' . $t->month . '\n'; # 结果:The month is Apr% perldoc -f X
_:用上次查询过的文件信息来做当前测试
if (-r $file and -w _) {...}if (-w -r $file) {...},先测试-r,后测试-w
-T和-B:测试某个文件是文本文件还是二进制文件。
但是对文件系统有一点经验的人都知道,(至少在Unix类似的操作系统下)没有任何地方会告诉你它是二进制文件还是文本文件,那么Perl是如何办到的呢?答案是Perl会作弊:
因此,它可能会有猜错的时候,所以这种猜测并不完美,不过如果你只想把编译过的文件和源文件分开,或是将HTML文件和PNG文件分开,那么这两种测试操作符还算够用。
你可能会认为-T和-B出现的结果必定相反,因为文件若不是文本文件,就该是二进制文件。但是,有两种特殊情况会让测试结果相同:
10 & 12
10 | 12
10 ^ 12
6 << 12
25 >> 2
~10
"\xAA" | "\x55":结果为"\xFF"chdir 'etc' or die "connot chdir to /etc: $!";FILE::HomeDirglob:my @all_files = glob '*.pm';
glob操作符的效果之所以和shell完全相同,是因为在Perl5.6以前它只不过是在后台调用/bin/csh来展开文件名。因此文件统配非常耗时,而且可能在目录太大时崩溃。当然,如果是新版本则无需担心此问题。my $dir_to_process = '/etc';
opendir my $dh, $dir_to_process
or die "Can't open $dir_to_process: $!";
foreach $file (readdir $dh)
{
print "one file in $dir_to_proces is $file\n";
}
close $dh;File::Find:Rule、File::Finder
rename 'old.txt' => 'new.txt';
rename 'over_there/some/place/some_file' => 'some_file';
linksymlinkreadlinkmy @result = sort &bynumber, @array;
sub by_number {
if ($a < $b) { -1 } elsif ($a > $b) { 1 } else { 0 };
}~~,可查看文档,"perlop"和"perlsyn"
system 'date';
# 通过使用参数来避免使用shell
my $tarfile = 'something*wicked.tar';
my @dirs = qw( fred|flintstone <barney&rubble> betty );
system 'tar', 'cvf', $tarfile, $tarfile, @dirs; # 也就是说参数最后回被引号括起来,并不会被shell解析,具体请查看perlfunc%ENVexec 'date';
die "date couldn't run: $!"system替代反引号,提高效率`date`; # system 'date'
# 好处:
# a. 避免对反引号转义use IPC::System::Simple qw( system systems captures )
my $tarfile = 'something*wicked.tar';
my @dirs = qw( fred|flintstone <barney&rubble> betty );
system 'tar', 'cvf', $tarfile, @dirs;
systemx 'tar', 'cvf', $tarfile, @dirs;
my @output = captures 'tar', 'cvf', $tarfile, @dirs;open DATE, 'date|' or die "can't pipe from date: $!";open MAIL, '|mail merlyn' or die "can't pipe to mail: $!"-|:读取的文件句柄,-相当于外部命令的占位符|-:写入的文件句柄,-相当于外部命令的占位符open my $date_fh, '-|', 'date' or die "can't pipe from date: $!"
open my $mail_fh, '|-', 'mail merlyn' or die "can't pipe to mail: $!"
my $now = <$date_fh>; # 开始执行并读取响应结果
print $mail_fh "the time is now $now"; # 写入邮件,假设$now以换行符结尾$?也会存储system和反引号圈引的命令的返回值
defined( my $pid = fork ) or die "Cannot fork: $!";
unless ( $pid )
{
# subprocess
exec 'date';
die "can't exec date: $!";
}
# parent process
waitpid( $pid, 0 );kill
kill 2, 4201 or die "can't signal 4201 with SIGINT: $!"; kill 'INT', 4201 or die "can't signal 4201 with SIGINT: $!"; kill INT => 4201 or die "can't signal 4201 with SIGINT: $!"; unless (kill 0, $pid) { warn "$pid has gone away!"; }$:一个元素@:一组元素%:一整个hash[]:访问列表(切片){}:访问hash元素eval块中出现致命错误时会立即停止运行整个块,然后退出继续运行其余的代码。
eval是一个表达式,所以末尾需要一个分号。
eval无法捕获到的错误
$@是一个特殊变量,而你所写的eval也许会被另一个高层的eval包裹,所以就要确保出现的错误不干扰高层出现的错误
{ local $@; # 不干扰高层错误 eval { ...; } ...; }use Try::Tiny
try
{
# 某些可能会抛出异常的代码
}
catch
{
# 某些处理异常的代码
}
finally
{
# 一定会指定的代码
}@dst_list grep { selector } @src_list;grep会将@src_list中的每个元素放到$_中并执行代码块selector,最后将返回真的元素以列表的形式返回,即@dst_listgrep返回符合过滤条件的元素个数map使用代码块中的最后一个表达式的实际计算结果,所以最终会返回一个这样的结果组成的列表。map使用的表达式(selector)是在一个列表上下文环境中,意味着可以一次返回多个元素的结果my @data = (4.75, 1.5, 2, 1234, 6.9456, 12345678.9, 29.95); print "The money number are:\n", map { sprintf("%25s\n", $_) } @data;
≡ var sidebarTOCBtn = document.getElementById('sidebar-toc-btn') sidebarTOCBtn.addEventListener('click', function(event) { event.stopPropagation() if (document.body.hasAttribute('html-show-sidebar-toc')) { document.body.removeAttribute('html-show-sidebar-toc') } else { document.body.setAttribute('html-show-sidebar-toc', true) } })