我总是很困惑或者不知道如何在perl中处理哈希。
所以这就是问题,
考虑到整个事情,我试图在下面的哈希中更改密钥名称。
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;
%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',
};
请帮助我解决这个问题!
答案 0 :(得分: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
等令人困惑的名称。这很好 - 令人困惑。