17

ループを通過せずにハッシュを初期化する方法を見つけようとしています。そのためにスライスを使用したいと思っていましたが、期待した結果が得られないようです。

次のコードを検討してください。

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

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

これは期待どおりに機能し、次の出力が生成されます。

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

次のようにスライスを使用しようとすると、機能しません。

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

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

出力は次のとおりです。

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

明らかに何かが間違っています。

だから私の質問は次のようになります: 2 つの配列 (キーと値) を指定してハッシュを初期化する最もエレガントな方法は何ですか?

4

4 に答える 4

24
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;
于 2010-08-24T11:54:13.637 に答える
15

したがって、必要なのは、キーの配列と値の配列を使用してハッシュを設定することです。次に、次の操作を行います。

#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper; 

my %hash; 

my @keys   = ("a","b"); 
my @values = ("1","2");

@hash{@keys} = @values;

print Dumper(\%hash);'

与えます:

$VAR1 = {
          'a' => '1',
          'b' => '2'
        };
于 2010-08-24T11:54:54.903 に答える
8
    %hash = ('current_symbol' => 'BLR', 'currency_name' => 'Real'); 

また

my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@fields} = @array x @fields;
于 2010-08-24T11:48:16.227 に答える
3

初めての方はお試しください

my %hash = 
( "currency_symbol" => "BRL",
  "currency_name" => "Real"
);
print Dumper(\%hash);

結果は次のようになります。

$VAR1 = {
          'currency_symbol' => 'BRL',
          'currency_name' => 'Real'
        };
于 2010-08-24T11:49:22.950 に答える