2017-02-28 57 views
0

如果存在並將其他數據存儲到數組,則嘗試跳過/ proc /分區文件中/ dev/raw文件中的所有設備。所以,我有如下代碼塊:在模式匹配中使用未初始化的值(m //)

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 

而此行是指:

next if $field[3] =~ /^ram/; 
+1

有可能是文件中的空行,然後現場#4不會如果你是在Linux上,像[Linux的::信息:: DiskStats(HTTPS定義 –

+0

。 org/pod/Linux :: Info :: DiskStats)可能會有用。 – ThisSuitIsBlackNot

回答

2

檢查數或假設所檢查的字段的缺省值。 // metacpan:

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