当用户在 Perl 中输入文本时,如何找到单词所在的行?

How do I find the line a word is on when the user enters text in Perl?

我有一个包含所有 50 个州的简单文本文件。我希望用户输入一个单词并让程序 return 文件中特定状态所在的行,否则显示 "word not found" 消息。我不知道如何使用查找。有人可以协助吗?这是我目前所拥有的。

#!/bin/perl -w

open(FILENAME,"<WordList.txt");             #opens WordList.txt
my(@list) = <FILENAME>;                     #read file into list
my($state);                                 #create private "state"     variable
print "Enter a US state to search for: \n"; #Print statement
$line = <STDIN>;                            #use of STDIN to read input from user


close (FILENAME);

这项工作的工具是 grep

 chomp ( $line ); #remove linefeeds 
 print "$line is in list\n" if grep { m/^\Q$line\E$/g } @list; 

您还可以将 @list 转换为散列,然后使用 map:

进行测试
 my %cities = map { $_ => 1 } @list; 
 if ( $cities{$line} ) { print "$line is in list\n";}

注意 - 以上,因为 ^$ 的存在是完全匹配(并且区分大小写)。您可以轻松调整它以支持更模糊的场景。

仅读取文件部分直到找到结果或文件耗尽的替代解决方案:

use strict;
use warnings; 

print "Enter a US state to search for: \n";
my $line = <STDIN>;
chomp($line);

# open file with 3 argument open (safer)
open my $fh, '<', 'WordList.txt'
   or die "Unable to open 'WordList.txt' for reading: $!";

# read the file until result is found or the file is exhausted
my $found = 0;
while ( my $row = <$fh> ) {
   chomp($row);
   next unless $row eq $line;

   # $. is a special variable representing the line number 
   # of the currently(most recently) accessed filehandle
   print "Found '$line' on line# $.\n"; 
   $found =  1;  # indicate that you found a result
   last;         # stop searching
}
close($fh);

unless ( $found ) { 
   print "'$line' was not found\n";
}

一般说明:

  • 总是 use strict;use warnings; 它们将使您免受各种错误的困扰

  • 3 参数 open 通常是首选,以及 or die ... 语句。如果您无法打开文件,从文件句柄读取将失败

  • $。文档可以在 perldoc perlvar

  • 中找到