typeglob 别名 [英] typeglob aliases

查看:65
本文介绍了typeglob 别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以很容易创建对数组的引用...

Okay, so it's easy to create a reference to an array...

my @a;
my $b=\@a;
#can now reference the same list of scalars from either @$b or @a

但是我怎么能反过来呢?例如:

But how can I do this in reverse? For instance:

my $a=[1..4];
my @b;
#some magic happens here and now @b is an alias for @$a
@b=(6..10);
print "@$a\n";  #should print "6 7 8 9 10"

我认为这会通过 typeglobs 发生,但那些只是逃避我.想法?

I assume this would happen through typeglobs, but those just elude me. Ideas?

对散列和数组也做同样的事情会很好.

Also it would be nice to do the same for hashes as well as arrays.

这似乎有效,但它有点笨拙,因为它只是将匿名数组元素复制到别名",然后将自身重新指向数组:

This seems to work, but it's a tad kludgy as it just copies the anon array elements to the "alias" and then re-points itself to the array:

my @b=@$a;
$a=\@b;

有更好的想法吗?

推荐答案

三种方式:

  1. 重新别名.

  1. Refaliasing.

5.22 添加了一个完全符合您要求的实验性功能.

5.22 added an experimental feature that does exactly what you want.

use experimental qw( refaliasing );
\my @B = $A;

5.26 添加了第二个实验性功能,可实现以下功能:

5.26 added a second experimental feature that allows the following:

use experimental qw( refaliasing declared_refs );
my \@B = $A;

请注意,作为实验性功能,这些功能可能会随时更改和删除.

Note that, being an experimental features, these features are subject to change and removal at any time.

全局别名

Perl 将其符号表条目数据结构称为type glob"或简称glob".可以将此数据结构中的条目设置为引用以命名该引用.

Perl calls "type glob", or "glob" for short, its symbol table entry data structure. It is possible to set the entries in this data structure to a reference to name that reference.

local our @B;
*B = $A;      # Sets the array slot of "B", @B.

注意我们必须使用一个包变量,所以这个变量是全局可见的.

Note that we have to use a package variables, so the variable is globally visible.

数据::别名

alias my @B = @$A;

这篇关于typeglob 别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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