Perl:“参考转移是实验性的" [英] Perl: "shift on reference is experimental"

查看:56
本文介绍了Perl:“参考转移是实验性的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取已排序哈希键列表的第一个元素.

I am trying to get the first element of a list of sorted hash keys.

这可以正常工作:

my $first = (sort keys %hash)[0];

这些没有

my $first = shift sort keys %hash;

my $first = shift (sort keys %hash); # just in case

它抛出错误

参考转移是实验性的.
不是 ARRAY 引用

shift on reference is experimental.
Not an ARRAY reference

这是怎么回事?

这是一个简单的操作,我无法弄清楚这个假定的参考在哪里.如果有引用,第一个语法将不起作用.

This is a simple operation and I can't figure out where this supposed reference is. If there were a reference the first syntax wouldn't work.

我通过脚本顶部的 use 使用 5.14 版.

I am using version 5.14 via use at the top of the script.

推荐答案

虽然这些术语经常互换使用,Perl 中的列表数组是有区别的.shift 操作符需要一个数组并且有修改数组的副作用.sort keys %hash 的结果是一个列表而不是一个数组,并且不是 shift 的有效参数.有一些技巧可以让 shift 处理任意列表

Though the terms are often used interchangeably, there is a distinction between a list and an array in Perl. The shift operator expects an array and has a side-effect of modifying the array. The result of sort keys %hash is a list but not an array, and is not a valid argument for shift. There are some hacks to get shift to work with an arbitrary list

 $x = shift @{[sort keys %hash]}      # for example

但是如果你调用 shift 只是因为你想要列表的第一个元素,那么有更简洁的方法来做到这一点.

but if you are calling shift just because you want the first element of the list, there are cleaner ways to do it.

my $first = (sort keys %hash)[0];
my ($first) = sort keys %hash;      # list context assignment
my $first = [sort keys %hash]->[0];

(我喜欢最后一个结构,但我不会判断它是否以错误的方式摩擦你)

(I like the last construction, but I don't judge you if it rubs you the wrong way)

实验性"问题是最新版本的 Perl 允许您在数组上调用 shift reference

The "experimental" issue is that recent versions of Perl allow you to call shift on an array reference

@a = (1,2,3); print shift @a;    # 1
$a = [4,5,6]; print shift $a;    # 4

当您在非命名数组上调用 shift 时,perl 假定您使用的是命令的 shift EXPR 形式,对数组引用进行操作.由于这是实验性的",因此您会收到警告.然后 perl 发现 shift 后面的内容实际上不是 ARRAY 引用,并且您会收到关于此的错误.

When you are calling shift on something that is not a named array, perl assumes you are using the shift EXPR form of the command, operating on an array reference. Since this is "experimental", you get a warning about that. Then perl discovers that what follows shift is not actually an ARRAY reference, and you get an error about that.

这篇关于Perl:“参考转移是实验性的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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