2013-11-01 61 views
1

我想使用构建一个哈希表来读取文件列表,并将每个值存储到哈希中,如下所示: - 打开目录并将它们列在数组中 - 然后打开每个文件,并从每个文件中的一些值,并把它们放到了桌子 文件名,总,通了,当我通过for循环,我得到运行它未能在哈希表如何使用Perl构建哈希表

#!/usr/bin/perl 
use strict; 

my $dir = "../result"; 
opendir(DIR, $dir) or die $!; 
my %result =(); 

while (my $file = readdir(DIR)) { 
    # We only want files 
    next unless (-f "$dir/$file"); 

    # do something here and get some value from each file 
    $total = $worksheet->get_cell(0,1); 
    $pass = $worksheet->get_cell(1,1); 
    $fail = $worksheet->get_cell(2,1); 

    # Print the cell value when not blank 
    $total = $total->value(); 
    $pass = $pass->value(); 
    $fail = $fail->value(); 


    %result = (
       "name" => "$file", 
       "total" => "$total", 
       "pass" => "$pass", 
       "fail" => "$fail" 
    ); 

} 

foreach my $key (keys %result) { 
    print "Key: $key, Value: $result{$key}\n"; 
} 

只有最后一个入口或最后一个文件的目录,我如何添加和建立散列,跟踪所有文件的密钥&上面提到的价值.. 在此先感谢..

+0

您可能想看看['File :: Find'](http://perldoc.perl.org/File/Find.html)模块 – jkshah

+0

您是否在程序的顶部放置了'use strict'避免告知?有它在那里很好,但你也需要声明你的变量。就目前而言,你的程序不会编译。 – Borodin

回答

1

您只会得到最后一个值,因为您每次都通过循环覆盖%result的值。

这听起来像你想要一个散列数组而不是单个散列。怎么样是这样的:

my @results; 
while (my $file = readdir(DIR)) { 
    ... 
    my %file_result = (
     "name" => "$file", 
     "total" => "$total", 
     "pass" => "$pass", 
     "fail" => "$fail" 
    ); 

    push @results, \%file_result; 
} 
+0

感谢它的作用就像一个魅力..你们是伟大 – user2912312

+0

@ user2912312,请确保您检查答案旁边的绿色复选标记,以表明它被接受。 – friedo

1

商店要在哈希什么:

相反的:

%result = (
       "name" => "$file", 
       "total" => "$total", 
       "pass" => "$pass", 
       "fail" => "$fail" 
    ); 

它取代每次整个哈希, 尝试类似:

$result{$file} = "$total $pass $fail"; 

在这种情况下,散列的键将是文件名, 和值连接的其他值的字符串。

您还可以使散列元素更复杂一些, 就像一个数组持有这三个值,或任何您可能需要的。

+0

@T G感谢它的魅力。你们很棒 – user2912312