【问题标题】:Perl push values in a hashPerl 在哈希中推送值
【发布时间】:2017-02-19 03:22:51
【问题描述】:

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

请帮我解决这个问题!

【问题讨论】:

  • 很抱歉,您将不得不扩大一点 - 我无法按照您的要求进行操作。我在您的代码示例中没有看到任何打印语句。
  • 你很好!我刚刚更新了打印语句
  • 我很困惑。你的输入和期望的输出是什么?
  • 我很抱歉造成混乱。更新了问题。希望你现在明白了!
  • 对于 hash 你需要括号 -- my %h = ( );如果您使用卷曲,则您正在使用 hash 引用,它是一个标量 -- my $rh = { ... }。你不能真的说%hash = { ... }(错误)。 yonyon100 的答案说明了这一点。在你的程序开始时使用use warnings;,你会听到这个。请始终use warnings;。

标签: perl hash perl-data-structures


【解决方案1】:

如果我对你的理解正确,那么这有效:

#!/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。这 - 好吧 - 令人困惑。

【讨论】:

  • 很抱歉变量混淆!它工作正常:)
猜你喜欢
  • 1970-01-01
  • 2015-11-28
  • 2010-10-20
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 2014-07-28
  • 2018-02-28
  • 2017-09-30
相关资源
最近更新 更多