Perl在哈希中推送值

时间:2016-10-10 16:32:18

标签: perl hash perl-data-structures

我总是很困惑或者不知道如何在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',
    };

请帮助我解决这个问题!

1 个答案:

答案 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等令人困惑的名称。这很好 - 令人困惑。