1

我对 Perl 编程很陌生;我在搜索从外部文本文件创建的数组时遇到了困难。我正在寻找一种简单的方法来检查用户条目是否位于数组中。我以前使用过 Smart Match 功能,但从未在“if”语句中使用过,而且似乎无法让它工作。我是否错误地实现了这个函数,或者有没有更简单的方法来检查用户的字符串是否在数组中?

#!/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";

}
4

1 回答 1

5

如果您想避免一起使用 smartmatch:

if ( grep { /$string1/ } @array ) {

然而,要真正匹配$string1,它需要被转义,所以这|并不意味着or

if ( grep { /\Q$string\E/ } @array ) {

或者只是一个简单的字符串比较:

if ( grep { $_ eq $string } @array ) {
于 2015-12-07T19:19:32.287 回答