在perl中使用未初始化的值

时间:2013-10-15 18:00:28

标签: regex perl

所以我有这段代码:

use warnings;
use strict;
my @arr = ("stuff (06:13)", "more stuff (02:59)", "extra stuff (00:00)");
my @new_arr = map { /\((\d+:\d+)\)/ ; $1 } @arr;
my ( $sum, $hrs, $mins );
$sum = 0;
for my $t (@new_arr) {
my ( $h, $m ) = split m/:/, $t;
my $hm = $h * 3600;
my $tm = $m * 60;
$sum = $sum + $hm + $tm;
}
$mins = sprintf( "%02d", ( $sum % 3600 ) / 60 );
$hrs  = int( $sum / 3600 );
print "$hrs:$mins\n";

我得到了未初始化的值错误

   Use of uninitialized value $t in split at DR/Hello World/test.pl line 14.
    Use of uninitialized value $h in multiplication (*) at DR/test.pl line 16.
    Use of uninitialized value $m in multiplication (*) at DR/test.pl line 17.

那我怎么解决这个问题?

2 个答案:

答案 0 :(得分:10)

stuff (3+06:13)/\((\d+:\d+)\)/不匹配,因此$1保持不变,因此$1包含undef,因此undef会在@arr中结束}。

在不确保模式匹配的情况下使用$1是不明智的。调整模式以确保它始终匹配,

/\(([\d+]+:\d+)\)/

或过滤掉不匹配的结果。

my @new_arr = map { /\((\d+:\d+)\)/ ? $1 : () } @arr;
  -or-
my @new_arr = map { /\((\d+:\d+)\)/ } @arr;

map { /\((\d+\++)/ ; $1 }存在类似问题。

答案 1 :(得分:3)

You're missing a capture in two of your regexes. 

你的第一个:

my @new_arr = map { /\((\d+:\d+)\)/ ; $1 } @arr;

错过了第一次捕获:

$VAR2 = [
          undef,
          '02:59',
          '00:00'
        ];

哪些可以纠正(见下文)。

你的第二次捕获也无法捕获任何东西:

my @x = map {/\((\d+\++)/ ; $1 } @arr;

见:

$VAR3 = [
          '3+',
          undef,
          undef
        ];

这是因为您要求它找到一个数字\d后跟一个文字+一次或多次,这只发生在$arr[0]中。如果没有找到捕获,我已调整为捕获0

#!/usr/bin/perl
use warnings;
use strict; 
use Data::Dumper;

my @arr = ("stuff (3+06:13)", "more stuff (02:59)", "extra stuff (00:00)");
my @new_arr = map { /\(.*?(\d+:\d+)\)/ ; $1 } @arr;
my @x = map {/\((\d+\+)|(0)/ ; $1 // $2 } @arr;
my ( $sum, $hrs, $mins );
$sum = 0;
for my $t (@new_arr) {
my ( $h, $m ) = split m/:/, $t;
my $hm = $h * 3600;
my $tm = $m * 60;
$sum = $sum + $hm + $tm;
}
$mins = sprintf( "%02d", ( $sum % 3600 ) / 60 );
$hrs  = int( $sum / 3600 );
print "$hrs:$mins\n";

print Dumper (\@arr, \@new_arr, \@x);


$VAR1 = [
          'stuff (3+06:13)',
          'more stuff (02:59)',
          'extra stuff (00:00)'
        ];
$VAR2 = [
          '06:13',
          '02:59',
          '00:00'
        ];
$VAR3 = [
          '3+',
          '0',
          '0'
        ];

输出:

9:12