perl学习笔记4

匹配FRED 时,也能匹配上fred, Fred,可以使用修饰符/i

点(.)不匹配换行符,这对于“单行中查找”的问题能很好解决。

如果你的字符串中有换行符,那可以使用/s 这个修饰符。

 $_="I saw Barney\ndown at the bowling alley\nwith Fred\nlast night.\n";
 if(/Barney.*Fred/s){
 print "That string mentions Fred after Barney!\n";
 }else{
 print "No matched!"
 }

 

/x 修饰符,允许你在模式中加入任何数量的空白,以方便阅读。

/-?\d+\.?\d*/ #这是什么含义?

/ -? \d+ \.? \d* /x #要好些

由于/x 允许模式中使用空白,那么模式中的空格,制表符将被忽略。

可以在空格前加上反斜线或者使用\t,但匹配空白更常用的方法是使用\s(\s*或\s+)。

符号^(脱字字符◆)表示在字符串的开头进行匹配,而符号$则表示在结尾。

词界锚定,\b,是针对单词使用的。如/\bfred\b/可以匹配上单词fred,但不能匹配frederick。

非词界锚定为\B。它将在任何非\b 匹配的点上进行匹配。

模式/\bsearch\B/将匹配searches, searching, searched, 但不能匹配search,或者researching。

 

绑定操作符,=~

对$_进行匹配只是默认的行为,使用绑定操作符(=~)将告诉Perl 将右边的模式在左边的字符串上进行匹配,而非对$_匹配。

其含义是:“这个模式默认将对$_进行匹配,但此时将对左边的字符串进行匹配”。如果没有绑定操作符,则此表达式将对$_匹配。

 my $some_other = "I dream of betty rubble.";
 if($some_other =~ /\brub/){
 print "Aye, there's the rub.\n";
 }else{
 print "No matched!";
 }

 

输入的字符不会自动存储在$_中,除非行输入操作(<STDIN>)单独出现在while 循环的条件判断部分。

 

模式内的内插

my $what = “larry”;

if(/^($what)/){ #在字符串前面进行匹配

...

 

在命令行中输入需要匹配的模式,使用参数@ARGV:

my $what = shift @ARGV;

 

三个奇怪的变量:

 if("Hello there,neighor"=~/\S(\w+),/){
 print "$&"."\n";
 print "$`"."\n";
 print "$'"."\n";
 }

输出:

there,
Hello
neighor

三个变量的值可能是空的。

 

如果结尾有两个或两个以上的换行符◆,chomp 仅去掉一个。

要分辨其是undef 还是空串,可以使用defined 函数,它将在为undef 时返回false,其余返回true。

 

列表值也可以赋给变量:

 

($fred, $barney, $dino) = (“flintstone”, “rubble”, undef);

($fred, $barney) = ($barney, $fred) #交换两个变量

 

可以使用如下的一行代码来创建按一个字符串数组:

($rocks[0],$rocks[1],$rocks[2],$rocks[3]) = qw/talc mica feldspar quartz/;

如果之前的$rocks[7]非空。那,这个赋值语句将不会改变其值。

@rocks = qw / bedrock slate lava /; #@rocks来引用整个数组。

@copy = @quarry; #将一个数组中的值拷贝的另一个数组中

 

pop 操作将数组的最后一个元素取出并返回:

@array = 5..9;

$fred = pop(@array); #$fred 得到9,@array 现在为(5,6,7,8)

push,它可以将一个元素(或者一列元素)加在数组的末尾:

push(@array,0); #@array 现在为(5,6,7,8,0)

push @array,1..10; #@array 现在多了10 个元素

 

push 和pop 对数组的末尾进行操作。

unshift 和shift 对一个数组的开头进行操作。

@array = qw# dino fred barney #;

$m = shift (@array); #$m 得到“dino”, @array 现在为(“fred”, “barney”)

unshift(@array,5); #@array 现在为(fred,barney,5)

 

@rocks = qw{ flintstone slate rubble };

print “quartz @rocks limestone\n”; #输出为5 种rocks 由空格分开

输出:quartz flintstone slate rubble limestone

 

Perl 最常用的默认变量:$_

 

foreach(1..10){ #使用默认的变量$_

print “I can count to $_!\n”;

}

 

@fred = 6 ..10;

@barney = reverse (@fred); #得到10,9,8,7,6

 

 

posted @ 2012-08-27 20:57  nalasun  阅读(145)  评论(0编辑  收藏  举报