匿名哈希切片 - 语法? [英] Anonymous Hash Slices - syntax?

查看:53
本文介绍了匿名哈希切片 - 语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢哈希切片并经常使用它们:

I love hash slices and use them frequently:

my %h;
@h{@keys}=@vals;

工作出色!但有两件事一直让我烦恼.

Works brilliantly! But 2 things have always vexed me.

首先,是否可以将上面的 2 行合并为一行代码?声明散列并一次性填充它会很好.

First, is it possible to combine the 2 lines above into a single line of code? It would be nice to declare the hash and populate it all at once.

其次,是否可以对现有的匿名散列进行切片……例如:

Second, is it possible to slice an existing anonymous hash... something like:

my $slice=$anonh->{@fields}

推荐答案

对于你的第一个问题,在一行代码中完成:

For your first question, to do it in a single line of code:

@$_{@keys}=@vals for \my %h;

map @$_{@keys}=@vals, \my %h;

但我不会那样做;这是一种令人困惑的编写方式.

but I wouldn't do that; it's a confusing way to write it.

任一版本都声明变量并立即引用它并将 $_ 别名为该引用,以便可以在切片中使用散列引用.这使您可以在现有范围内声明变量;@{ \my %h }{@keys} = @vals; 也有效",但不幸的缺点是将 %h 范围限定到哈希中的那个小块切片.

Either version declares the variable and immediately takes a reference to it and aliases $_ to the reference so that the hash reference can be used in a slice. This lets you declare the variable in the existing scope; @{ \my %h }{@keys} = @vals; also "works", but has the unfortunate drawback of scoping %h to that tiny block in the hash slice.

对于你的第二个问题,如上所示,切片可以用于散列引用;参见 http://perlmonks.org/?node=References+quick+reference一些容易记住的规则.

For your second question, as shown above, slices can be used on hash references; see http://perlmonks.org/?node=References+quick+reference for some easy to remember rules.

my @slice = @$anonh{@fields};

或者你的意思是:

my $slice = [ @$anonh{@fields} ];

但是@slice/$slice 有一个值的副本.要获取哈希值的别名数组,您可以执行以下操作:

but @slice/$slice there is a copy of the values. To get an array of aliases to the hash values, you can do:

my $slice = sub { \@_ }->( @$anonh{@fields} );

这篇关于匿名哈希切片 - 语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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