我有两个字符串,例如$must
和 $is
。它们在开始时应该是相同的。但是如果有错误,我想知道在哪里。
例子:
my $must = "abc;def;ghi";
my $is = "abc;deX;ghi";
位置 6 上的“X”不相等,所以这是我需要的结果。
所以我需要类似的东西
my $count = count_equal_chars($is, $must);
结果是“6”,因为字符 0 到 5 相等。
(如果是“5”也没关系,因为写++
没问题。)
到目前为止我的代码:
编辑:添加了解决方法。
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
my $head_spec = "company;customer;article;price"; # specified headline
my $count = 0; # row counter
while (<DATA>) {
s/[\r\n]//; # Data comes originally from Excel ...
if (!$count) {
# Headline:
## -> error message without position:
##print "error in headline\n" unless ($head_spec eq $_);
## -> writeout error message with position:
next if ($head_spec eq $_);
# Initialize char arrays and counter
my @spec = split //, $head_spec; # Specified headline as character-array
my @is = split //, $_; # Readed headline as character-array
my $err_pos = 0; # counter - current position
# Find out the position:
for (@spec) {
$err_pos++, next if $is[$err_pos] eq $_;
last;
}
# Writeout error message
print "error in headline at position: $err_pos\n";
}
else {
# Values
print "process line $count, values: $_\n";
}
}
continue { $count++; }
__DATA__
company;custXomer;article;price
Ser;0815;4711;3.99
Ser;0816;4712;4.85
背景:
背景是,有一个带有很长标题(> 1000 个字符)的 .csv 文件。此 header 指定。
如果其中有错误,则该文件有错误,必须由用户编辑。
所以告诉他错误在哪里很有用,这样他就不需要比较整行了。
最佳答案
使用xor
,^
,算子可以找到错误的位置。在连续字母匹配的地方,异或运算给出 \0
.
$-{0]
是 last match start variable (对于上一行中的正则表达式, (($must ^ $is) =~/[^\0]/
)。
你可以这样找到位置:
#!/usr/bin/perl
use strict;
use warnings;
my $must = "company;customer;article;price";
my $is = "company;custXomer;article;price";
($must ^ $is) =~ /[^\0]/; # find first non-matching character
print "Error position is ", $-[0]; # position of first non-matching char
打印:12
关于string - 如何获取字符串开头对应字符的个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67584968/