|
发表于 2003-12-2 15:59:35
|
显示全部楼层
#!perl -w
#这行是不是有错误,Perl程序的路径,好象应该是#!/usr/bin/perl -w,windows上不需要
while(<> ) {
#<>表示从键盘读取输入的数据,<>是输入操作符,缺省为STDIN
chomp;
#截去\n,等价为 chomp $_; Perl中的所有函数的默认参数可能为 $_,@_等
if (/string/) {
#正则表达式,相当于$_ ~= /string/m;
print "Matched:|$`<$&>$'|\n";
#最复杂的就是这里了
} else {
print "No match.\n";
}
}
最后面几行,看文档中的介绍,特殊变量
$PREMATCH
$`
The string preceding whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK). (Mnemonic: ` often precedes a quoted string.) This variable is read-only.
The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches.
$POSTMATCH
$'
The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). (Mnemonic: ' often follows a quoted string.) Example:
local $_ = 'abcdefghi';
/def/;
print "$`&'\n"; # prints abc:def:ghiThis variable is read-only and dynamically scoped to the current BLOCK.
The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches.
$MATCH
$&
The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). (Mnemonic: like & in some editors.) This variable is read-only and dynamically scoped to the current BLOCK.
The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. |
|