选自《Perl 语言入门(第六版)》习题。
写个程序,输出含有要求单词的行。要求的单词用大写字母开头,但并非全大写。
此程序是否会匹配含有 Fred 的行,而不匹配含有 fred 或 FRED 的行?
代码如下:
#!/usr/bin/perl
use 5.012;
my $file_name = $ARGV[0];
open my $words_fh, '<', $file_name
or die "Cannot open file '$file_name'!";
my $linecnt = 1;
while (<$words_fh>) {
chomp;
if (/[A-Z]+[a-z]+([A-Za-z])*/) {
printf "%3d: ", $linecnt;
say;
}
$linecnt += 1;
}
say "End of reading...";
测试用到的文件 words.txt:
this is FRED.
fred is my friend;
FrED is hardworking.
FRed has a little dog.
fRED likes reading books.
mutual trust is the BEDROCK of a relationship.
honesty is the bedrock of any healthy relationship.
beneath the soil lies a layer of BEDrock.
YES, there's plenty of room.
Yes, that's a good point.
yes, I worte the article. What of it?
i need a simple yes or NO to my questions.
No admittance.
no relief drivers were available.
运行结果如下:
% ./ex7-4 words.txt
3: FrED is hardworking.
4: FRed has a little dog.
8: beneath the soil lies a layer of BEDrock.
10: Yes, that's a good point.
11: yes, I worte the article. What of it?
13: No admittance.
End of reading...