arrays - 我将如何使用散列切片来初始化存储在数据结构中的散列?

标签 arrays perl hash slice

在之前的一个问题中,我询问了如何使用切片初始化 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/

相关文章:

javascript - 尝试找出如何使用 "this"寻址各个菜单项

python - numpy:在二维数组中找到对称值

Perl JSON 模块 |无法获得 JSON 响应

arrays - 在 Perl 中从数组中删除值的最佳方法是什么?

security - 密码哈希值的非随机盐

algorithm - 什么是好的哈希函数?

c - 数组 C 的动态内存分配

java - 如何将此 float[] vertexData 添加到 Vector3f 列表?

javascript - 我需要进行 Ajax 调用并显示数据库表的内容,我正在使用 Perl CGI 并尝试通过 javaScript 调用 Perl 脚本

javascript - 解密 Javascript 中的字符串