2016-09-16 58 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) { 
     # ... 
    } 
} 

是有相当多的,可以在代码中提高,但会采取我们在其他地方。