【问题标题】:how to solve "Use of uninitialized value $2 in concatenation (.) or string at"如何解决“在连接 (.) 或字符串 at 中使用未初始化的值 $2”
【发布时间】:2019-11-07 16:52:56
【问题描述】:

下面是我的代码。我想在一行中打印数据 $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);

【问题讨论】:

  • 我已经修正了你代码的缩进。不客气,但请以后自己做。良好的缩进是使代码易于理解的最佳工具之一。如果你要让大量陌生人阅读和理解你的代码,那么让他们尽可能简单是礼貌的做法。
  • 谢谢。 @DaveCross。抱歉,这是我的第一个 perl 脚本。
  • 良好缩进的重要性并不是 Perl 独有的。如果您明智地缩进,您使用的几乎任何编程语言都会更容易阅读。

标签: regex perl


【解决方案1】:

你的程序的核心在这里:

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...
      }
    }
    

【讨论】:

  • 与其建议使用$_,因为它是一个被所有东西使用的超全局,容易受到隐藏问题的影响,我只是将其更改为while (my $line = &lt;$fh&gt;),因此根本不使用$_。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
相关资源
最近更新 更多