# map
%map=("key","value","key2", "value2");
注:用列表给关联数组赋值时,Perl5允许使用"=>"或","来分隔下标与值,用"=>"可读性更好些,上面语句等效于:
%fruit = ("apples"=>17,"bananas"=>9,"oranges"=>"none");
##取map 的值
$map{"key"} =value;
## add
$map{"key3"}="v3";
## delete
delete ($map{"key"});
each 取出map中每个键值对, 这种方式比foreach与keys()合作 快
%map=("a","b", "c","d" );
while (($k,$v) = each(%map)){
print("$k:$v\n");
$line='abcabcde';
@result =split(/c/ , $line); #result= ("ab" ,"ab" ,"de")
foreach $ele (@result){
print($ele ,"\n");
$result =split(/c/ , $line);
print($result); # result =3
缺省的,模式定界符为反斜线/,但其可用字母m自行指定,如:
m!/u/jqpublic/perl/prog1! 等价于/\/u\/jqpublic\/perl\/prog1/
$pattern = "[\\t ]+";
@words = split(/$pattern/, $line);
在模式匹配后调用重用部分的结果可用变量$n,全部的结果用变量$&。
$string = "This string contains the number 25.11.";
$string =~ /-?(\d+)\.?(\d+)/; # 匹配结果为25.11
$integerpart = $1; # now $integerpart = 25
$decimalpart = $2; # now $decimalpart = 11
$totalpart = $&; # now totalpart = 25.11
@matches = "balata" =~ /.a/g; # now @matches = ("ba", "la", "ta")
匹配的循环:
while ("balata" =~ /.a/g) {
$match = $&;
print ("$match\n");
/a.*bc/s匹配字符串axxxxx \nxxxxbc,但/a.*bc/则不匹配该字符串。
两者都是进行替换操作,区别是前者用正则表达示,后者:
tr/searchment/repalcement/;是把searchment的第一个字符换成replacement的第一
个字符,searchment的第二个字符换成replacement的第二个字符,类推
$line="abcab";
$line =~ s/ab/d/ ;
print($line);
结果为: dcab
$line="abcab";
$line =~ s/ab/d/g ;
print($line);
结果为 : dcd
区别是正则表达式后加一个g ,表示global ,即不仅仅进行一次替换,如果字符串中
出现多处匹配正则的,所有匹配均予考虑
tr/searchment/repalcement/;是把searchment的第一个字符换成replacement的第一
个字符,searchment的第二个字符换成replacement的第二个字符,类推
$line='abcDeF';
$line =~ tr/abc/ABC/;
print($line);
结果:ABCDeF
&two_array_sub (*array1, *array2);
sub two_array_sub {
my (*subarray1, *subarray2) = @_;
open (STDOUT, ">file1") || die ("open STDOUT failed");
open (STDERR, ">&STDOUT") || die ("open STDERR failed");
print STDOUT ("line 1\n");
print STDERR ("line 2\n");
close (STDOUT);
close (STDERR);
open (a, ">file1") || die ("open STDOUT failed");
open (b, ">&a") || die ("open STDERR failed");
print a ("line 1\n");
print b ("line 2\n");
close (a);
close (b);
把值1赋给系统变量"$|"
系统变量"$|"指定文件是否进行缓冲而不管其是否应该使用缓冲。
如果$|为非零值则不使用缓冲。$|与系统变量\(~和\)协同工作,当未调用select函
数时,$|影响当前缺省文件
open (STDOUT, ">file1") || die ("open STDOUT failed");
open (STDERR, ">&STDOUT") || die ("open STDERR failed");
$| = 1; # 因未调用select(),当前的缺省文件为重定向到文件file1的STDOUT ,
# 此将$|=1 , 意为stdout不用缓冲区
select (STDERR);
$| = 1;
print STDOUT ("line 1\n");
print STDERR ("line 2\n");
close (STDOUT);
close (STDERR);
打开一个既可读又可写的文件方法是在文件名前加上"+>",如下:
open (READWRITE, "+>file1");
此语句打开既可读又可写的文件file1,即可以重写其中的内容。文件读写操作最好与库函数seek和tell一起使用,这样可以跳到文件任何一点。
注:也可用前缀"+<"指定可读写权限
print是这三个函数中最简单的,它向指定的文件输出,如果未指定,则输出到当前缺省文件中,如:
print ("Hello, there!\n");
print OUTFILE ("Hello, there!\n");
第一句输出到当前缺省文件中,若未调用select,则为STDOUT。第二句输出到由文件变量OUTFILE指定的文件中。
printf函数先格式化字符串再输出到指定文件或当前缺省文件中,如:
printf OUTFILE (“You owe me %8.2f", $owing);
此语句取出变量$owing的值并替换掉串中的%8.2f,%8.2f是域格式的例子,把$owing的值看作浮点数。
write函数使用输出格式把信息输出到文件中,如:
select (OUTFILE);
$~ = "MYFORMAT";
write;
eof函数查看最后一次读文件操作是否为文件最后一个记录,如果是,则返回非零
值,如果文件还有内容,返回零。一般情况下,对eof的调用不加括号,因为eof和
eof()是等效的,但与<>操作符一起使用时,eof和eof()就不同了。现在我们来创
建两个文件,分别叫做file1和file2。file1的内容为
while ($line = <STDIN>) {
print ($line);
if (eof) {
print ("-- end of current file --\n");
&open_file("INFILE", "", "file1");
&open_file("OUTFILE", ">", "file2");
while ($line = &read_from_file("INFILE")) {
&print_to_file("OUTFILE", $line);
sub open_file {
local ($filevar, $filemode, $filename) = @_;
open ($filevar, $filemode . $filename) ||
die ("Can't open $filename");
sub read_from_file {
local ($filevar) = @_;
<$filevar>;
sub print_to_file {
local ($filevar, $line) = @_;
print $filevar ($line);
seek和tell中文件变量参数可使用表达式。
opendir (tmpdir, "/tmp/") ||print "die";
@fs=readdir (tmpdir);
foreach my $f ( @fs){
print $f ,"\n" ;
return sub {
my $msg = shift; # Define the error type now.
print "Err Level $lvl:$msg\n"; }; # print later.
$severe = errorMsg("Severe");
$fatal = errorMsg("Fatal");
$annoy = errorMsg("Annoying");
&$severe("Divide by zero");
&$fatal("Did you forget to use a semi-colon?");
&$annoy("Uninitialized variable in use");
sub spitOut {
my $filehandle=shift;
print $filehandle "Gee Wilbur, I like this lettuce\n";
$line = ['solid', 'black', ['1','2','3'] , ['4', '5', '6']];
print "\$line->[0] = $line->[0] \n";
print "\$line->[2][0] = $line->[2][0] \n";
模块(module)就是Perl包(pachage) 扩展名pm是包的缺省扩展名,意为Perl Module
一个Perl类是仅是一个包而已。当你看到Perl文档中提到“类”时,把它看作
“包”就行了
保留“1;”为最后一行。这是Perl包的必需条件
可以用单引号(')操作符来定位类中的变量,类中成员的定位形式如:
Perl5中,可用双冒号替代单引号
$class'$member
$class::$member
# 4、一定不要在类模块中使用全局变量。
sub new {
my $this= {} Create an anonymous hash, and #self points to it.
bless $this # bless($this) # Connect the hash to the package Cocoa.
return $this; # Return the reference to the hash.
;1 #这一行必须为放在最后一行
创建一个Cocoa 对象
push (@INC,'pwd'); # 将当行路径加到include 下
use Cocoa; #在@INC 下搜寻Cocoa.pm 并include 之
# 三种创建对象的方法
$cup = new Cocoa; 创建一个对象
$cup = Cocoa->new();
$cup = Cocoa::new(); # 如果你是C程序员,可以用双冒号强制使用Cocoa包中的new()函数,如:
@list = ("perl","Regular","network","web");
#可以等价于:
@list = qw(perl Regular network web);
@list = qw{perl Regular network web};
$myword = "cnangel";
$replaceword = qr(cnangel);
$finalword = "ok" if ($myword =~ $replaceword);
# qr{whatever} 与qr(whaterver) 与/whatever/同
$var =~ /h(el)lo/ ;
print ($& ,"\n"); # print "hello"
print ($`, "\n"); # print "before"
print ($', "\n"); # print 'after'
print ($1, "\n"); # print "el"
open(file , "/tmp/b.pl");
while($line = <file>){
print ( "当前是第" , $. , "行,内容是:", $line,"\n");
$_ is known as the "default input and pattern matching space". In other words, if you read in
from a file handle at the top of a while loop, or run a foreach loop and don't name a loop
variable, $_ is set up for you. Then any regular expression matches, chops (and lcs and many
more) without a parameter, and even prints assume you want to work on $_. 就是说如果从一个文件用
while 或foreach 读取一行内容, 而你没用一个变量存变读取到的这一行,那么,默认把它放到$_ 变量中。
不仅如此,任何像match chos print 等操作的函数,默认以它作参数,如果你没指定的话因此
open(file , "/tmp/b.pl");
while($line = <file>){
print ( "当前是第" , $. , "行,内容是:", $line,"\n");
有这样一段内容,把们把$/ 设成 %%\n时,如此从此文件读数据时<file> 读的不再是一行,而是靠%%分隔的内
而chmop()函数,要从一个字符串删除的内容,也是这个变量里指定的内容
但是当你修改了这些特殊变量的值后,你会得到一个警告
因为你有可能忘记把它恢复原值,而使其他部分的程序可能产生bug
好的做法是local 化之
{ # 注意到没,可以把一段代码放在{} 块中,而其中的local变量,在外不起作用
local $/ = "%%\n";
open(QUOTE, "/tmp/a.java");)
while (<QUOTE>) {
chomp;
print;
另外如果将$/ 置空的话,则从一个文件中读取内容时则一次读取整个文件
my $file = do { local $/; <FILE> };
又如果,$/ 值是一个数字的指针时,则一次读取这个数字的大小的字节数
local $/ = \2048; # 一次读取2k
while (<FILE>) {
# $_ contains the next 2048 bytes from FILE
第一个操作数(“..“左侧的表达式)将被求值,如果得出的值为假,此次操作将什么也不做并
返回假值。
如果得出的值为真,操作返回真值并继续依次返回下面的值直到第二个操作数(“..”操作符右面
的表达式)返回真值 .注意到 “直到” 这两个字没有
也就是说可以把它用作if 后的括号中做真假判断
比如java 中的代码注释以 /* 为开头 */为结束
我现在想取出这种代码中的这种注释。
我可以把判断 当前行中包不包括 * 作为第一个操作数,而把判断当前行包不包括* 作为第二个操作数
就是说,如果遇到/* 就满足了if 条件,开始作if 里的操作,做完一次操作就判断一下第二个操作数满不满
足,如果满足的话,停止,否则,继续
open(FILE,"/tmp/a.java");
while (<FILE>) {
if ( m!/\*! .. m!\*/!){
print $_ ;