下面是我的代码。我想在一行中打印数据$1和$2,并使用,
将其拆分。为什么我不能打印数据?
#!/usr/intel/bin/perl
use strict;
use warnings;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
my $input = "par_disp_fabric.all_max_lowvcc_qor.rpt.gz";
my $output = "par_disp_fabric.all_max_lowvcc_qor.txt";
gunzip $input => $output
or die "gunzip failed: $GunzipError\n";
open (FILE, '<',"$output") or die "Cannot open $output\n";
while (<FILE>) {
my $line = $_;
chomp ($line);
if ($line =~ m/^\s+Timing Path Group \'(\S+)\'/) {
$line = $1;
if ($line =~ m/^\s+Levels of Logic:\s+(\S+)/) {
$line = $2;
}
}
print "$1,$2\n";
}
close (FILE);
发布于 2018-10-01 14:44:54
你的程序的要点在这里:
if ($line =~ m/^\s+Timing Path Group \'(\S+)\'/) {
$line = $1;
if ($line =~ m/^\s+Levels of Logic:\s+(\S+)/) {
$line = $2;
}
}
正则表达式捕获变量($1
、$2
等)是在将字符串与包含捕获括号集的正则表达式进行匹配时设置的。第一个捕获括号设置$1
的值,第二个捕获括号设置$2
的值,依此类推。为了给$2
赋值,您需要匹配一个包含两组捕获括号的正则表达式。
这两个正则表达式只包含一组捕获括号。因此,只会在每个匹配项上设置$1
。$2
将永远不会被赋予一个值-导致您看到的警告。
您需要重新考虑代码中的逻辑。我不知道为什么你会认为$2
在这里有价值。您的代码有点混乱,所以我无法提供更具体的解决方案。
然而,我可以给你一些更一般的建议:
open()
的三参数版本。打开我的$fh,'<',$output
周围的引号不需要"$output"
open my $fh,'<',$output
$output
可能是一个容易混淆的名字。考虑更改它。
open()
错误消息中包含$!
。打开我的输出,'<',$output或die“无法打开‘$ $fh’:$!\n”;
$line
变量似乎不必要。为什么不将行数据保存在$_
中,这将简化您的代码:而(<$fh>) { chomp;#默认适用于$_,如果(/some regex/) {#默认适用于$_ #等等...} }
https://stackoverflow.com/questions/52593229
复制相似问题