在之前的一个问题中,我询问了如何使用切片初始化 Perl 哈希。它是这样完成的:
my %hash = ();
my @fields = ('currency_symbol', 'currency_name');
my @array = ('BRL','Real');
@hash{@fields} = @array;
现在让我们想象一个更复杂的散列,这是它的初始化方式:
my %hash = ();
my $iso = 'BR';
$hash->{$iso}->{currency_symbol} = 'BRL';
$hash->{$iso}->{currency_name} = 'Real';
print Dumper($hash);
这导致以下结果:
$VAR1 = {
'BR' => {
'currency_symbol' => 'BRL',
'currency_name' => 'Real'
}
};
现在的问题是:如何使用 splice 方法初始化这个特定的哈希?
最佳答案
perllol documentation's Slices section覆盖数组切片:
If you want to get at a slice (part of a row) in a multidimensional array, you're going to have to do some fancy subscripting. That's because while we have a nice synonym for single elements via the pointer arrow for dereferencing, no such convenience exists for slices. (Remember, of course, that you can always write a loop to do a slice operation.)
Here's how to do one operation using a loop. We'll assume an
@AoA
variable as before.@part = (); $x = 4; for ($y = 7; $y < 13; $y++) { push @part, $AoA[$x][$y]; }
That same loop could be replaced with a slice operation:
@part = @{ $AoA[4] } [ 7..12 ];
外推到哈希切片,我们得到
@{ $hash{$iso} }{@fields} = @array;
你知道它是一个散列切片,因为“下标”被花括号而不是方括号包围。
关于arrays - 我将如何使用散列切片来初始化存储在数据结构中的散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3556524/