2016-10-10 91 views
1

我总是感到困惑或不知道如何在Perl中处理哈希。Perl推送哈希值

所以现在的问题是,

考虑整个事情,我试图在下面的哈希更改密钥名称。 %new_hash的

my %hash_new = { 
    'customername' => 'Lee & toys', 
    'employee_name' => 'Checngwang', 
    'customer_id' => 'X82349K', 
    'customer_address' => 'classic denver ranch, meadows drive', 
    'types' => 'category la', 
}; 

my %selectCols = ('customername' => 'CUSTOMERNAME','employee_name' => 'EMP_NAME','customer_id' => 'cusid','customer_address' => 'cusaddr','types' => 'Typs'); 

my %new_hash =(); 

foreach my $hash_keys (keys %hash_new){ 
    my $newKey = $selectCols{$hash_keys}; 
    $new_hash{$newKey} = $hash_new{$hash_keys}; 
} 

print Dumper %new_hash; 

输出是一样的东西连续串如下的键值组合,

CUTOMERNAMELee & toysEMP_NAMEChecngwangcus_idX82349Kcusaddrclassic denver ranch, meadows driveTypscategory la 

但不是这个,我需要的哈希一样,

$VAR1 = { 
     'CUSTOMERNAME' => 'Lee & toys', 
     'EMP_NAME' => 'Checngwang', 
     'cusid' => 'X82349K', 
     'cusaddr' => 'classic denver ranch, meadows drive', 
     'Typs' => 'category la', 
    }; 

请帮助我解决这个问题!

+1

对不起,你将不得不扩大一点 - 我不能跟随你所问的。我的代码示例中没有看到任何打印语句。 – Sobrique

+0

你很好!我刚刚更新了打印声明 – Raja

+0

我很困惑。你的输入是什么?期望的输出是什么? – yonyon100

回答

0

如果我理解正确的话,那么这个作品:

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dumper; 


my %hash_new = (
    'customername' => 'Lee & toys', 
    'employee_name' => 'Checngwang', 
    'customer_id' => 'X82349K', 
    'customer_address' => 'classic denver ranch, meadows drive', 
    'types' => 'category la' 
); 

my %selectCols = (
    'customername' => 'CUSTOMERNAME', 
    'employee_name' => 'EMP_NAME', 
    'customer_id' => 'cusid', 
    'customer_address' => 'cusaddr', 
    'types' => 'Typs' 
); 

my %new_hash =(); 

foreach my $hash_keys (keys %hash_new){ 
    my $newKey = $selectCols{$hash_keys}; 
    $new_hash{$newKey} = $hash_new{$hash_keys}; 
} 

print Dumper \%new_hash; 

我在你的代码更改的唯一代码使用(),而不是在%hash_new{}和逃脱的Dumper声明%。应该转义%,因为Dumper需要引用,而不是散列(对于使用Dumper的所有其他Perl变量类型也是如此)。

输出:

$VAR1 = { 
     'Typs' => 'category la', 
     'cusaddr' => 'classic denver ranch, meadows drive', 
     'EMP_NAME' => 'Checngwang', 
     'cusid' => 'X82349K', 
     'CUSTOMERNAME' => 'Lee & toys' 
    }; 

另外,不要使用令人混淆的名字,如%hash_new%new_hash。这很好 - 令人困惑。

+0

我很抱歉变量混乱!它工作正常:) – Raja

+0

@Yadheendran没有伤害做:) – yonyon100