小白自学Perl,笔记
Perl语言入门,第17章习题第一题。
#! /usr/bin/perl -w
use strict; #编译指令,提高编译约束力,减小脚本容错值。
use v5.16; #指定Perl版本
use autodie; #指定Perl负责自动抛出异常,相当于die指令
my $count=0;
my @matches;
my $filename='sample_text.txt';#记得字符串赋值给标量要带上单或双引号
open my $fh, '<', $filename;
chomp(my @strings= <$fh>); #这样会将文件存入内存里,方便读取。
while(1)
{
say "please print your pattern:";
chomp(my $pattern=<STDIN>);
exit if $pattern eq ''; #标准输入输入空白行则退出
eval #eval用于捕获错误
{
foreach (@strings)
{
if ($_=~/$pattern/)
{
push @matches, $_; #将所匹配的行放进数组@matches里面
$count++;
}
}
};
if($@) #eval产生的错误会放在特殊变量$@里面。
{
print "Error:$@";
}
else
{
foreach (@matches)
{
say $_;
}
say "There were $count matching strings:";
}
}