【问题标题】:extract string within double quote from the line in a file从文件中的行中提取双引号内的字符串
【发布时间】:2014-09-22 23:18:36
【问题描述】:

我的文件内容为:

Component (0463) "commonfiles"
Component (0464) "demo_new_comp"
Component (0467) "test_comp" (removed)
Component (0469) "test_comp3" (removed)
Component (0465) "textfiles1

需要从具有(已删除)的每一行中提取双引号内的字符串并将其放入数组中。 我的代码是:

my $fh = new IO::File;
$fh->open("<comp.log") or die "Cannot open comp.log";
my @comp_items;
while (<$fh>) {
    if ( $_ =~ /removed/ ) {;
        my $compName = $_ = ~ m/"(.*?)"/;
        print " Componnet Name : \"$compName\"\n";
    }
}

我没有得到正确的输出,给出一些数字:

"18446744073709551614"
"18446744073709551614"

输出应该是:

test_comp
test_comp3

【问题讨论】:

  • 不应该是my ( $compName ) = ...吗?

标签: perl


【解决方案1】:
my $compName = $_ = ~ m/"(.*?)"/;

= ~=~ 不同,但赋值和bitwise negation

而你想要的是,

my ($compName) = $_ =~ m/"(.*?)"/;

或者只是,

my ($compName) = /"(.*?)"/;

【讨论】:

  • 这将输出为:Componnet Name : "1"Componnet Name : "1"
  • 如果这是答案,请将此答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
相关资源
最近更新 更多