首页 > 解决方案 > Perl - 未初始化的变量警告

问题描述

我正在努力找出我在这里做错了什么。

我的代码的目标是读取一个文件,movie_script.txt然后使用正则表达式根据说出该行的字符将每一行排序到一个数组中。它确实有效,但我在这些警告之前得到了输出:

Use of uninitialized value $char in string eq at filter.pl line 24, <$fh> line 13.
Use of uninitialized value $char in string eq at filter.pl line 26, <$fh> line 13.
Use of uninitialized value $char in string eq at filter.pl line 28, <$fh> line 13.
[...]
 Hello, mother.
 Oh. Well-- well, I, uh--
 Well, uh, I think they must have popped by for something.
 Mm, they-- they started following me yesterday.

这是代码:

use strict;
use warnings;

my $filename = "movie_script.txt";

unless (-e $filename) {
    print "Error: File does not exist.";
}

my @brian;
my @mandy;
my @followers;

open(my $fh, '<', $filename);

my $match = qr/^(\w+):(.+)$/i;

while (my $line = <$fh>) {
    my $char = "";
    my $scriptline = "";
    if ($line) {
       ($char, $scriptline) = $line =~ $match;

        if ($char eq "BRIAN") {
            push(@brian, $scriptline);
        } elsif ($char eq "MANDY") {
            push(@mandy, $scriptline);
        } elsif ($char eq "FOLLOWERS") {
            push(@followers, $scriptline);
        } else {
            print($line);
        }
    }
}

foreach (@brian) {
    print "$_\n";
}

我怀疑问题是一行不适合我的正则表达式,它导致变量$charand出现问题$scriptline,但我不知道如何确认这是否属实,或者如何找出导致问题的行。

我尝试使用 运行 Perl 调试器perl -d,但是当我继续执行每一行时,我找不到错误。我试图在 `else { print($line) } 行周围设置一个断点,但我无法弄清楚如何运行调试器,直到它到达该行。

我的代码中是否有明显的原因导致我遇到未初始化的值问题?

标签: regexperlinitialization

解决方案


考虑让 Perl 告诉您问题所在。

if ($line) {
   if (my ($char, $scriptline) = $line =~ $match) {
     # Your existing code here
   } else {
     warn "Line [$line] doesn't match the regex [$match]\n";
   }

请注意,我还将$charand的声明移到了$scriptline尽可能小的范围内。更早地声明它们或预先填充它们是没有意义的(因为您将覆盖匹配行中的数据)。


推荐阅读