regex - 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";
}
我怀疑问题是一行不适合我的正则表达式,它导致变量$char
and出现问题$scriptline
,但我不知道如何确认这是否属实,或者如何找出导致问题的行。
我尝试使用 运行 Perl 调试器perl -d
,但是当我继续执行每一行时,我找不到错误。我试图在 `else { print($line) } 行周围设置一个断点,但我无法弄清楚如何运行调试器,直到它到达该行。
我的代码中是否有明显的原因导致我遇到未初始化的值问题?
解决方案
考虑让 Perl 告诉您问题所在。
if ($line) {
if (my ($char, $scriptline) = $line =~ $match) {
# Your existing code here
} else {
warn "Line [$line] doesn't match the regex [$match]\n";
}
请注意,我还将$char
and的声明移到了$scriptline
尽可能小的范围内。更早地声明它们或预先填充它们是没有意义的(因为您将覆盖匹配行中的数据)。
推荐阅读
- r - 在 MGCV 包 RStudio 中使用 MRF 创建预测回归方程
- c++ - PlatformIO中外部环境变量的访问
- r - ggplot2中的geom_tile返回空白图
- java - 无响应的套接字读取缓冲区
- java - 尝试启动我的 Spring Boot 应用程序时,即使我设置了它们,我也需要谷歌凭据
- ios - 将 TableViewCell 传递给新的 TableView(在顶部)Swift
- javascript - 如何使用 moment.js 将日期时间字符串转换为一分钟前/一天前/一个月前/一年前格式
- react-admin - 如何从 blob URL 转换为二进制文件?
- python - 找不到按钮元素、硒、python
- javascript - 有没有办法将本地 json 文件加载到 localstorage 中?