我怎么没有初始化一个循环的哈希值? [英] How do I initialize values in a hash without a loop?

查看:131
本文介绍了我怎么没有初始化一个循环的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图想出一个办法来初始化一个哈希,而无需经过一个循环。我希望用切片一点,但它似乎并没有产生预期的结果。

考虑以下code:

 #!的/ usr / bin中/ perl的
使用数据::自卸车;我散列%=();
$ {哈希} CURRENCY_SYMBOL ='BRL';
$ {哈希CURRENCY_NAME} ='真实';
打印自卸车(%哈希);

这确实工作的期望和产生下面的输出:

  $ VAR1 ='CURRENCY_SYMBOL';
$ VAR2 ='B​​RL';
$ VAR3 ='CURRENCY_NAME';
$ VAR4 ='真实';

当我尝试如下使用切片,这是行不通的:

 #!的/ usr / bin中/ perl的
使用数据::自卸车;我散列%=();
我@fields =('CURRENCY_SYMBOL','CURRENCY_NAME');
我@array =(BRL','真正的');
@hash {@array} = @fields点¯x@array;

输出是:

  $ VAR1 ='CURRENCY_SYMBOL';
$ VAR2 =22;
$ VAR3 ='CURRENCY_NAME';
$ VAR4 =民主基金;

有显然是有些不妥。

所以我的问题是:什么是初始化给定一个散列两个数组(键和值)最优雅的方式


解决方案

 使用严格的;
使用警告; # 必需品#...你初始化数组我@fields =('CURRENCY_SYMBOL','CURRENCY_NAME');
我@array =(BRL','真正的');#...分配给您的散列我散列%;
@hash {} @fields = @array;

I am trying to figure out a way to initialize a hash without having to go through a loop. I was hoping to use slices for that, but it doesn't seem to produce the expected results.

Consider the following code:

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

my %hash = ();
$hash{currency_symbol} = 'BRL';
$hash{currency_name} = 'Real';
print Dumper(%hash);

This does work as expect and produce the following output:

$VAR1 = 'currency_symbol';
$VAR2 = 'BRL';
$VAR3 = 'currency_name';
$VAR4 = 'Real';

When I try to use slices as follows, it doesn't work:

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

my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@array} = @fields x @array;

The output is:

$VAR1 = 'currency_symbol';
$VAR2 = '22';
$VAR3 = 'currency_name';
$VAR4 = undef;

There is obviously something wrong.

So my question would be: what is the most elegant way to initialize a hash given two arrays (the keys and the values)?

解决方案

use strict;
use warnings;  # Must-haves

# ... Initialize your arrays

my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');

# ... Assign to your hash

my %hash;
@hash{@fields} = @array;

这篇关于我怎么没有初始化一个循环的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆