我更喜欢编程Perl;我在搜索我从外部文本文件制作的数组时遇到了困难。我正在寻找一种简单的方法来检查用户条目是否位于数组中。我之前使用过智能匹配功能,但从未使用过智能匹配功能,如果"声明似乎无法使其发挥作用。我是否实现了这个函数错误,或者是否有更简单的方法来检查用户的字符串是否在数组中?
#!/usr/bin/perl
use 5.010;
#Inventory editing script - Jason Black
#-------------------------------------------------------------------------------
print "1. Add Items\n";
print "2. Search Items\n";
print "Please enter your choice: ";
chomp ($userChoice = <STDIN>); #Stores user input in $userChoice
if($userChoice == 1){
$message = "Please enter in format 'code|title|price|item-count'\n";
&ChoiceOne;
}
elsif($userChoice == 2){
$message = "Enter search terms\n";
&ChoiceTwo;
}
sub ChoiceOne{
print "$message\n";
chomp($userAddition = <STDIN>); #Stores input in $userAddition
$string1 = "$userAddition";
open (FILE, "FinalProjData.txt") or die ("File not found"); #"FILE" can be named anything
@array = <FILE>;
if ( /$string1/ ~~ @array){
print "This entry already exists. Would you like to replace? Y/N \n";
chomp($userDecision = <STDIN>); #Stores input in $userDecision
if ($userDecision eq "Y"){
$string1 =~ s/$userAddition/$userAddition/ig;
print "Item has been overwritten\n";}
elsif($userDecision eq "N"){
print FILE "$string1\n";
print "Entry has been added to end of file.\n";}
else{
print "Invalid Input";
exit;}
}
else {
print FILE "$string1\n";
print "Item has been added.\n";}
close(FILE);
exit;
}#end sub ChoiceOne
sub ChoiceTwo{
print "$message\n";
}
答案 0 :(得分:5)
如果你想完全避免使用smartmatch:
if ( grep { /$string1/ } @array ) {
要实际匹配$string1
,它必须是escaped,因此|
并不代表or
:
if ( grep { /\Q$string\E/ } @array ) {
或只是一个简单的字符串比较:
if ( grep { $_ eq $string } @array ) {