如何获取数组中元素的索引? [英] How to get the index of an element in an array?

查看:735
本文介绍了如何获取数组中元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl是否具有内置函数来获取数组中元素的索引?还是我需要自己编写这样的功能? [相当于PHP array_search()或JavaScript array.indexOf()]

Does Perl have a build-in function to get the index of an element in an array? Or I need write such a function by myself? [ equivalent to PHP array_search() or JavaScript array.indexOf() ]

推荐答案

use List::Util qw(first);
$idx = first { $array[$_] eq 'whatever' } 0..$#array;

(List :: Util是核心)

(List::Util is core)

use List::MoreUtils qw(firstidx);
$idx = firstidx { $_ eq 'whatever' } @array;

(列表:: MoreUtils位于CPAN上)

(List::MoreUtils is on CPAN)

这篇关于如何获取数组中元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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