gpt4 book ai didi

perl 相等的字符串即使相等也返回 0

转载 作者:行者123 更新时间:2023-12-02 07:47:19 24 4
gpt4 key购买 nike

Perl 不断给我带来惊喜。我有一个代码,它从命令行获取输入并检查它是否在文件中。我有一个这样的文件:

日期

密码

触摸

首先我读这个文件是

open(MYDATA,"filename") or die "Can not open file\n";
@commandlist = <MYDATA>;
chomp @commandlist;
close MYDATA;

参数在 $commandname 变量中。为了检查它是否正确,我打印到屏幕上。

print $commandname."\n";

效果很好。然后我写代码。

$count = @commandlist;
for($i=0;$i < $count;$i++)
{
print $commandname;
print $commandlist[$i];
print "\n";
if($commandname eq $commandlist[$i])
{
print "equal\n";
}
}

并且它不打印“等于”。但它应该这样做,因为 $commandname 变量的值“ls”在文件中。我还打印了 $commandname 和 $commandlist[$i] 的值,看看它们是否“明显”相等,我得到了输出:

ls
lsls
lsdate
lspwd
lstouch
lsrm

在这里我看到它们得到了相同的值,但为什么 eq 运算符的计算结果从来没有为零。此外,为了完成这项任务,我尝试了各种方法,所有这些方法都变得毫无用处,比如从数组中创建散列并使用 exists。我为这个看似简单的问题苦苦挣扎了一天,但我就是不明白。提前致谢

编辑:当我如下更改上述循环时

$count = @commandlist;
for($i=0;$i < $count;$i++)
{
print $commandlist[$i];
print $commandname;
print "\n";
if($commandname eq $commandlist[$i])
{
print "equal\n";
}
}

我得到了这样的输出。

ls
ls
lste
lsd
lsuch
ls

似乎出于某种原因它覆盖了一些字符。

编辑:

我的整个脚本是这样的:

#reading file code, i posted above
while(<>)
chomp($_);
$commandname = $_;
if($commandname eq "start"){
##something here
} elsif ($commandname eq "machines"){
##something here
} else {

$count = @commandlist;
for($i=0;$i < $count;$i++)
{
print $commandlist[$i];
print $commandname;
print "\n";
if($commandname eq $commandlist[$i])
{
print "equal\n";
}
}

}

最佳答案

代码中的一点更改将导致您正在寻找的内容,在将其放入进行比较之前从数组中“截断”字符串。在这里

chomp $commandlist[$i];

if($commandname eq $commandlist[$i])
{
print "equal\n";
}

编辑:根据 perldoc chomp当你在咀嚼一个列表时,你应该加上括号。所以,在你的情况下......而不是简单地说

chomp @commandlist 

让它变得像

chomp(@commandlist)

最终编辑:我试过了,效果很好。试一试

$commandname = $ARGV[0];

open(MYDATA,"chk.txt") or die "Can not open file\n";
@commandlist = <MYDATA>;
chomp(@commandlist);
close MYDATA;

print $commandname."\n";

$count = @commandlist;
print $commandname;
for($i=0;$i < $count;$i++)
{

print $commandlist[$i];
print "\n";
if($commandname eq $commandlist[$i])
{
print "equal\n";
}
}

关于perl 相等的字符串即使相等也返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6038342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com