如何从在 Perl 中返回数组的函数中获取第一项? [英] How do I get the first item from a function that returns an array in Perl?

查看:176
本文介绍了如何从在 Perl 中返回数组的函数中获取第一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数组的函数,我只想从该数组中获取第一项,而无需为该数组声明变量.基本上,它应该是这样的:

I have a function that returns an array, and I'd like to get just the first item from that array without ever declaring a variable for the array. Basically, it should be something like:

functionReturningArray()[1]

除非那不起作用.

我真的不想浪费空间声明整个数组,因为我不需要它,而且我不想浪费额外的一行代码.无论如何要在一行中做到这一点?

I really don't want to waste space declaring the whole array since I don't need it, and I'd rather not waste an extra line of code. Anyway to do this in one line?

推荐答案

my $item = (function_returning_list())[0];

函数不能返回数组,它们可以返回数组的内容(即列表).列表从 0 开始索引,所以函数返回的第一项是 (func)[0].你也可以说

Functions cannot return arrays, they can return the contents of an array (i.e. a list). Lists are indexed starting at 0, so the first item of a function's return is (func)[0]. You could also say

my ($item) = function_returning_list();

这将 function_returning_list 放在列表上下文中,并对左侧列表中的变量进行赋值(按顺序).

This puts function_returning_list in list context and does assignment (in order) to the variables in the left-hand-side list.

需要注意的是

sub function_returning_list {
    return ("a", "b", "c")
}

my $item = function_returning_list();

可能不会做您期望的事情.$item 变量将被分配c".这是因为在标量上下文中没有列表这样的东西.相反,您在标量上下文中有逗号运算符,它在 void 上下文中计算左侧表达式,丢弃结果,然后在标量上下文中计算右侧.

will likely not do what you expect. The $item variable will be assigned "c". This is because there is no such thing as a list in scalar context. Instead, you have the comma operator in scalar context, and that evaluates the lefthand expression in void context, discards the result, then evaluates the righthand side in scalar context.

我调用一个序列(而不是一个列表),如果像 C 风格的 for 循环这样的一些情况,它会很有用.

I call a sequence (rather than a list) and is useful if a few situations like C-style for loops.

这篇关于如何从在 Perl 中返回数组的函数中获取第一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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