regex - 另外使用未初始化值 $1 - Perl

标签 regex perl

我正在编写一个有点模仿 UNIX 中最后一个命令的程序,并且我尝试在我的解决方案中使用反向引用。我的程序完全按照预期执行,但我收到运行时错误/警告。我的问题是为什么会出现此错误/警告以及如何解决这样的问题?

如果您需要更多信息,我可以提供。

程序执行

./last dodoherty

输出

Here is a listing of the logins for dodoherty:

1. dodohert pts/1        pc-618-012.omhq. Wed Feb  8 09:19   still logged in
2. dodohert pts/6        ip98-168-203-118 Tue Feb  7 19:19 - 20:50  (01:31)
3. dodohert pts/3        137.48.207.178   Tue Feb  7 14:00 - 15:06  (01:05)
4. dodohert pts/1        137.48.219.250   Tue Feb  7 12:32 - 12:36  (00:04)
5. dodohert pts/21       137.48.207.237   Tue Feb  7 12:07 - 12:23  (00:16)
6. dodohert pts/11       ip98-168-203-118 Mon Feb  6 20:50 - 23:29  (02:39)
7. dodohert pts/9        ip98-168-203-118 Mon Feb  6 20:31 - 22:57  (02:26)
8. dodohert pts/5        pc-618-012.omhq. Fri Feb  3 10:24 - 10:30  (00:05)
Use of uninitialized value $1 in addition (+) at ./odoherty_last.pl line 43.
Use of uninitialized value $2 in addition (+) at ./odoherty_last.pl line 44.
Here is a summary of the time spent on the system for dodoherty:

dodoherty
8
8:6

代码(错误来源的片段,也是唯一一次使用 $1 和 $2。)

foreach my $line2 (@user)
{
        $line2 =~ /\S*\((\d{2,2})\:(\d{2,2})\)\s*/;
        $hours = $hours + $1;
        $mins = $mins + $2;

        if( $mins >= 60 )
        {
                $hours = $hours + 1;
                $mins = $mins - 60;
        }
}

最佳答案

我认为问题可能出在下面一行。

1. dodohert pts/1 pc-618-012.omhq。 2 月 8 日星期三 09:19 仍处于登录状态

这是因为没有任何内容与模式匹配,因此 $1 和 $2 未定义。

关于regex - 另外使用未初始化值 $1 - Perl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9196349/

相关文章:

perl - 从文件中获取列名

perl - 您如何处理 Perl Web 应用程序中的鼠标控制?

perl - 对哈希值的数组引用进行排序

javascript - 将 Sed 函数转变为 JavaScript 正则表达式

php - 如果数组包含字符串则排除数组

database - DBI:如何为未知数据找到正确的数据类型?

perl - 如何测试其中包含 'exit'的子例程(perl)

regex - bash 。使用参数名称创建 var 并清除其值

javascript - 在 highcharts 中转义单引号

javascript - 如何使用 Regex 将字符串中的所有数字四舍五入?