2016-09-16 88 views
2

問候語我試圖按照本教程將文件讀入散列哈希。

http://docstore.mik.ua/orelly/perl/prog3/ch09_04.htm

我的文字輸入文件

event_a1_x1: [email protected] [email protected] email1_cnt=3 
event_a1_x2: [email protected] [email protected] email1_cnt=3 
event_b2_y1: [email protected] [email protected] email1_cnt=3 
event_b2_y2: [email protected] [email protected] email1_cnt=3 
event_c3_z1: [email protected] [email protected] email1_cnt=3 
event_c3_z2: [email protected] [email protected] email1_cnt=3 

我的代碼是

#!/usr/bin/perl 
use strict; 
use warnings; 

my $file = $ARGV[0] or die "Need to get config file on the command line\n"; 

open(my $data, '<', $file) or die "Could not open '$file' $!\n"; 

my %HoH; 
#open FILE, "filename.txt" or die $!; 
my $key; 
my $value; 
my $who; 
my $rec; 
my $field; 

while (my $line = <$data>) { 
    print $line; 
    next unless (s/^(.*?):\s*//); 
    $who = $1; 
    #print $who; 
    $rec = {}; 
    $HoH{$who} = $rec; 
    for $field (split) { 
     ($key, $value) = split /=/, $field; 
     $rec->{$key} = $value; 
    } 
} 

我不斷收到這個錯誤...

Use of uninitialized value $_ in substitution (s///) at ./read_config.pl line 18, <$data> line 1. 
+0

您已分配給'$ line',因此您不能再使用'$ _'。所以'下一個除非$ line =〜s /...//',並且'split line'在下面的'$ line'。或者,刪除'my $ line'(和所有其他'$ line's,只是'print;')。繼續閱讀好書,這段代碼可以改進很多。 – zdim

回答

5

這是什麼時候$_,「默認輸入和模式搜索空間」,被設置和使用。

while (<$fh>)中,將從文件句柄讀取的內容分配給$_。然後你的正則表達式s///printsplit可以使用它。見General Variables in perlvar

但是,一旦我們專門分配給一個變量,while (my $line = <$fh>),此交易關閉,並且$_未設置。因此,當您稍後以依賴於$_的方式使用正則表達式替換時,變量將被找到uninitialized

要麼一致地使用默認$_,要麼(一致地)不使用。所以,要麼

while (<$fh>) { 
    print; 
    # same as posted 
} 

while (my $line = <$fh>) { 
    # ... 
    next unless $line =~ s/^(.*?):\s*//; 
    # ... 
    foreach my $field (split ' ', $line) { 
     # ... 
    } 
} 

是有相當多的,可以在代碼中提高,但會採取我們在其他地方。

相關問題