简体   繁体   English

获取 function 返回的列表的第一项

[英]Get the first item of the list returned by function

A simple simulation of the problem:问题的简单模拟:

use strict;
use warnings;

sub uniq
{
  my %seen;
  grep !$seen{$_}++, @_;
}

my @a = (1, 2, 3, 1, 2);

print shift @{uniq(@a)}; 

Can't use string ("3") as an ARRAY ref while "strict refs" in use在使用“strict refs”时不能使用字符串(“3”)作为 ARRAY ref

Need to impose a list context on the function call, and then pick the first element from the list.需要在 function 调用上施加一个列表上下文,然后从列表中选取第一个元素。

The print , or any other subroutine call, already supplies a list context. print或任何其他子例程调用已经提供了列表上下文。 Then one way to extract an element from a returned list然后一种从返回列表中提取元素的方法

print +( func(@ary) )[0];

This disregards the rest of the list.这忽略了列表中的 rest。

That + is necessary (try without it), unless we equip print itself with parentheses around all its arguments, that is那个+是必要的(不用它试试),除非我们用括号围绕它的所有 arguments 来装备print本身,即

print( (func(@ary))[0] );

One option could be to return an array reference:一种选择是返回一个数组引用:

sub uniq {
  my %seen;
  [grep !$seen{$_}++, @_];
}

If uniq returned an array reference, then @{uniq(...)} would be the correct idiom to get an array (which is a suitable argument for shift ).如果uniq返回数组引用,那么@{uniq(...)}将是获取数组的正确习惯用法(这是shift的合适参数)。 For a more general list, you can cast the list to an array reference and then dereference it.对于更通用的列表,您可以将列表转换为数组引用,然后取消引用它。

print shift @{ [ uniq(@a) ] };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM