【问题标题】:Use of uninitialized value in pattern match (m//)?在模式匹配(m//)中使用未初始化的值?
【发布时间】:2013-09-02 07:58:37
【问题描述】:

我查看了有关此问题的其他答案,但仍不确定为什么会遇到此问题:在模式匹配中使用未初始化的值 (m//)

my $curr = 0;
my (@up_intf, @nh_ID);
my $line = "";
for (my $index = 0; $index < length(@lines); $index++) {
       $line = $lines[$index];
       print("The line is: $line");
       if (($line =~ /^Group:/i)) {
          while (1) {
             if (($line =~ /^Uptime:/i)) { last; }
             else {
               $index++;
               $line = $lines[$index];
               if (($line =~ /^Downstream/i)) {
                  $index++;
                  $line = $lines[$index];
                  print($line);
                  $up_intf[$curr] = $line;
               }
               if (($line =~ /^Next-hop/i)) {
                  $nh_ID[$curr] = substr($line, 13, ((length($line) - 13)));
                  print($line);
                  $curr++;
               }
              }
            }
        }
}

谢谢!

【问题讨论】:

  • 你认为$index &lt; length(@lines) 是做什么的?另请参阅Loopy Validation ... 长话短说,忘记while(1)

标签: regex string perl matching


【解决方案1】:

你的循环应该是:

for (my $index = 0; $index < $#lines; $index++) {

还有很多其他的问题,但这是一个起点。

$#lines 给出@lines 的最后一个索引,而scalar @lines 给出@lines 中元素的数量。 length @lines 并没有按照你的想法去做。

查看你的循环:

           if (($line =~ /^Downstream/i)) {
              $index++;
              $line = $lines[$index];
              print($line);
              $up_intf[$curr] = $line;
           }

如果最后一行匹配/^Downstream/i 怎么办?然后将未定义的值分配给 $line 并继续:

          if (($line =~ /^Next-hop/i)) {
              $nh_ID[$curr] = substr($line, 13, ((length($line) - 13)));
              print($line);
              $curr++;
           }

您会在哪里收到警告。

由于没有更好的术语,您进行处理的方式很古怪。

【讨论】:

  • 最好写成for my $i ( 0..$#lines ) { ;)
  • 当然,但我想一次解决一件事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2021-03-22
  • 1970-01-01
  • 2012-06-20
  • 2021-06-22
  • 1970-01-01
相关资源
最近更新 更多