我有一个包含所有50个州的简单文本文件。我希望用户输入一个单词并让程序返回文件中特定状态所在的行,否则显示“未找到单词”消息。我不知道怎么用find。有人可以协助吗?这是我到目前为止所做的。
#!/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);
答案 0 :(得分:6)
另一种解决方案,只读取文件的各个部分,直到找到结果或文件耗尽:
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参数,以及or die ...
语句。如果您无法打开文件,则从文件句柄中读取将失败
$。文档可以在perldoc perlvar
答案 1 :(得分:1)
工作的工具是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";}
注意 - 上面的内容,因为^
和$
的存在是完全匹配(并且区分大小写)。您可以轻松调整它以支持更模糊的场景。