2016-05-27 76 views
-1

我是Perl新手,试图找出实现此目的的最佳方式,但目前还不确定语法。Hadoop的Perl哈希/阵列实现

我现在的脚本正在读HDFS中的一个文件,该文件包含许多可能性中的关键值对。

例如,让我们说,我可以有从A,B,C,d,E

范围的键,我从阅读该文件将换行分隔的样子:

A,50 
C,30 

在我的脚本中,我想读取文件并将变量分配给相应的值,如果有任何变量不存在,我想将它们赋值为零值。

因此,由脚本的最后,我想有一个打印像这样的输出:

A=50,B=0,C=30,D=0,E=0 

随着我在Perl有限的知识,我不知道如何设置最佳的环路收集这样的信息会是?我有读取文件的功能,但没有收集度量值到某种Array或Hash分组。

+0

请出示你写的代码 – Borodin

回答

1
use strict; 
use warnings; 

my @keys = qw(A B C D E);  
open my $fh, '<', $filename_from_hdfs 
    or die "$!"; 

my %mapping; 
while (my $line = readline($fh)) { 
    chomp($line); 
    my ($key, $value) = split /,/, $line; 

    $mapping{$key} = $value; 
} 

# zero out keys with no value 
$mapping{$_} //= 0 foreach @keys; 

print join(',', map { "$_=$mapping{$_}" } sort keys %mapping), "\n"; 
1
my %result; 
#assign zero to all keys 
for my $key ('A' .. 'E') 
{ 
$result{$key} = 0; 
} 
#open file, read each line one by one 
#Split each read line from file in ($key, $value). 
result{$key} = $value; 

#After finishing reading the file, traverse %result and output key, values