- 论坛徽章:
- 0
|
本帖最后由 无双六 于 2012-11-17 18:36 编辑
习题如下:
写一个程序,从文件中读入字符串,一行一个字符串,然后让用户输入模式,这个模式可能匹配上某些字符串。对于每一个模式,程序将指出文件中有多少个字符串(多少行)匹配上了,并指出是哪些。对于新的模式不需要重新读文件,将这些字符串保留在内存中。文件名可以直接写在程序之中。如果模式无效(例如,圆括号不匹配),则程序报告这个错误,并让用户继续尝试新的模式。当用户输入一个空行,则程序退出。
给出的答案如下:- #!usr/bin/perl
- use 5.014;
- use utf8;
- use strict;
- my $filename = 'sample_text.txt';
- open my $fh, '<', $filename
- or die "Can't open '$filename': $!";
- chomp(my@strings = <FILE>);
- while (1) {
- print 'please enter a pattern:';
- chomp (my$pattern = <STDIN>);
- last if $pattern=~ /\A\s*\Z/;
- my @matches = eval {
- grep /$pattern/, @strings;
- };
- if ($@) {
- print "Error: $@";
- } else {
- my$count = @matches;
- print "there were $count matching stings:\n",
- map "$_\n", @matches;
- }
- print "\n";
- }
复制代码 我运行这个程序总是零匹配,而且在我看来貌似是错了,比如"<FILE>"是哪里来的。。
我自己写的如下:- #!usr/bin/perl
- use 5.014;
- use utf8;
- use strict;
- use autodie;
- eval(open my$story_fh, '<', 'sample_text.txt');
- while (1) {
- say "Please input your word:";
- chomp(my$input = <STDIN>);
- last if $input =~ /\A\s*\z/;
- my@match = eval { grep /\b$input\b/i, <$story_fh> };
- if ($@) {
- say "Error: $@";
- } else {
- my$count = @match;
- print "$count successed match , they are:\n", @match, "\n";
- }
- }
- close $story_fh;
复制代码 第一次匹配成功,但之后就都匹配失败,都是零次了。
望高人指点。 |
|