在模式匹配(m //)中使用未初始化的值

时间:2017-02-28 22:15:13

标签: regex perl file debugging

我尝试在/ proc / partitions文件中跳过/ dev / raw启动的所有设备(如果存在)并将其他设备存储到数组中。所以我有一段代码,如:

None

此代码将返回如下错误:

sub get_proc_partitions {
    my ($self, $device_name) = @_;
    my @partitions;

    open(PART, "/proc/partitions") || die "can't open /proc/partitions: $!";
    while (<PART>) {
        my @field = split;
        # Skip this line if the fourth field starts with 'ram'
        next if $field[3] =~ /^ram/;
        # this regex matches lines like the following.
        # in this example it will capture hdb
        #   3    64   78150744 hdb 157 735 2168 1720 1745 437 17432 
        if (/^\s*(?:\d+\s+){3}(\S+)\s.*/) {
            my $part = $1;
            if ( defined $device_name ) {
                push(@partitions, $part) if ($part =~ /$device_name/);
            } else {
                push(@partitions, $part);
            } 
         }
      }
close(PART);
return \@partitions;
}

这一行指的是:

 Use of uninitialized value in pattern match (m//) at <filename> line 928, <PART> line 2

2 个答案:

答案 0 :(得分:2)

当我发出cat /proc/partitions时,第二行为空:

$ cat /proc/partitions 
major minor  #blocks  name

   1        0      65536 ram0
   1        1      65536 ram1
 ...

我想是你的。在next unless /\S/;后面插入while以跳过空行:

while (<PART>) {
    next unless /\S/;   # skip empty lines
    my @field = split;
    ...

答案 1 :(得分:2)

检查通过拆分检测/生成的字段数或假设已检查字段的默认值。

#  "@field <4" - less than four fields 
next if @field <4 || $field[3] =~ /^ram/;