【问题标题】:Perl string from regex is different from created string - breaks fgrep来自正则表达式的 Perl 字符串与创建的字符串不同 - 中断 fgrep
【发布时间】:2015-04-10 15:38:35
【问题描述】:

我有一段代码正在检查文件中的文件名是否存在于主列表中,但它一直说字符串不存在时 - 但如果我用文件名声明第二个变量它 - 手动输入 - 效果很好。

来自正则表达式的变量与我声明的变量不同(它们看起来相同)。我检查了这一点,但使用 Perl 的自动类型解析,我不知道问题出在哪里。

...
open (my $fh_in, $in_file) or die "Could not open file $in_file $!";

seek ($fh_in, 5995, 0);
my $line = readline ($fh_in);
$line =~ /"([^"]*)"/;  # extracts the filename from a Filename="..." field
my $adf_file = $1;

if (fgrep { /$adf_file/ } "masterlist.txt" ) {
  print "The file is in the master list\n";
} else {
  print "It isn't\n";
}

它说该文件不在主列表中。 如果我这样做:

my $testst = "File_I_Want";

fgrep { /$testst/ }   ...

它说文件在主列表中。

如果我再比较一下:

if ($testst eq $adf_file) {
  print "variables are the same\n";
} else {
  print "variables are not the same\n";
}

正在打印它们不同但看起来相同。

提前感谢您的帮助。

【问题讨论】:

  • use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper $adf_file; 显示结果。
  • 是的,这样做。它将显示$adf_file 中的所有不可打印字符。
  • 非常感谢。我会记住未来的 - 有一些尾随空格。 $VAR1 = "ASA_CON_AXVIEC20120626_153045_20030601_000000_20050916_195733";

标签: regex perl grep


【解决方案1】:

如果您添加,这将有助于查看两个字符串之间的差异

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper $adf_file;

设置Useqq 选项使Data::Dumper 以双引号样式显示字符串,对所有不可打印的字符使用转义序列。

更好的是Data::Dump,它只需要

use Data::Dump;
dd $adf_file;

做同样的事情。它还可以生成更易读的嵌套数据结构显示,但它不是核心模块,可能需要安装。

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2021-07-28
    • 1970-01-01
    • 2020-05-06
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 2021-07-19
    相关资源
    最近更新 更多