如何解决"Use of uninitialized value $2 in concatenation (.) or string at"



下面是我的代码。我想在一行中打印数据 $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: $GunzipErrorn";
open (FILE, '<',"$output") or die "Cannot open $outputn";
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,$2n";
}
close (FILE);

你的程序的肉在这里:

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()的三参数版本。

    open my $fh, '<', "$output"
    
  • $output周围不需要引号.

    open my $fh, '<', $output
    
  • 我知道你为什么要这样做,但对于你从中读取的文件来说,$output是一个可能令人困惑的名称。考虑更改它。

  • 始终在open()错误消息中包含$!

    open my $fh, '<', $output or die "Cannot open '$output': $!n";
    
  • 您的$line变量似乎没有必要。为什么不直接将行数据保存在$_中,这将简化您的代码:

    while (<$fh>) {
    chomp; # works on $_ by default
    if (/some regex/) { # works on $_ by default
    # etc...
    }
    }
    

最新更新