在Perl中,如何在数组中找到给定值的索引?

Ant*_*pes 14 arrays perl

$VAR1 = [
          '830974',
          '722065',
          '722046',
          '716963'
        ];
Run Code Online (Sandbox Code Playgroud)

如何计算值"722065"的数组索引?

too*_*lic 33

List :: MoreUtils中firstidx函数可以帮助:

use strict;
use warnings;
use List::MoreUtils qw(firstidx);

my @nums = ( '830974', '722065', '722046', '716963' );
printf "item with index %i in list is 722065\n", firstidx { $_ eq '722065' } @nums;

__END__
Run Code Online (Sandbox Code Playgroud)
item with index 1 in list is 722065

  • 我喜欢使用List :: MoreUtils,很好的答案! (6认同)

new*_*cct 24

使用List::Util,这是一个核心模块,不像List::MoreUtils,不是:

use List::Util qw(first);

my @nums = ( '830974', '722065', '722046', '716963' );
my $index = first { $nums[$_] eq '722065' } 0..$#nums;
Run Code Online (Sandbox Code Playgroud)


Sin*_*nür 14

以下是如何找到给定值出现的所有位置:

#!/usr/bin/perl

use strict;
use warnings;

my @x = ( 1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1 );
my @i = grep { $x[$_] == 3 } 0 .. $#x;
print "@i\n";
Run Code Online (Sandbox Code Playgroud)

如果您只需要第一个索引,则应使用List :: MoreUtils :: first_index.

  • 这是Perl街头的债券材料,以为:-) (2认同)

dao*_*oad 7

如果您只需要查找一个项目,请firstidx像其他人所说的那样使用.

如果需要进行多次查找,请构建索引.

如果您的数组项是唯一的,那么构建索引非常简单.但是构建一个处理重复项目的方法并不困难.以下两个例子如下:

use strict;
use warnings;

use Data::Dumper;

# Index an array with unique elements.
my @var_uniq  = qw( 830974 722065 722046 716963 );
my %index_uniq  = map { $var_uniq[$_] => $_ } 0..$#var_uniq;

# You could use hash slice assinment instead of map:
# my %index_uniq;
# @index_uniq{ @var_uniq } = 0..$#var_uniq

my $uniq_index_of_722065   = $index_uniq{722065};
print "Uniq 72665 at: $uniq_index_of_722065\n";
print Dumper \%index_uniq;

# Index an array with repeated elements.
my @var_dupes = qw( 830974 722065 830974 830974 722046 716963 722065 );
my %index_dupes;
for( 0..$#var_dupes ) {
    my $item = $var_dupes[$_];

    # have item in index?
    if( $index_dupes{$item} ) {
        # Add to array of indexes
        push @{$index_dupes{$item}}, $_;
    }
    else {
        # Add array ref with index to hash.
        $index_dupes{$item} = [$_];
    }
}

# Dereference array ref for assignment:
my @dupe_indexes_of_722065 = @{ $index_dupes{722065} };

print "Dupes 722065 at: @dupe_indexes_of_722065\n";
print Dumper \%index_dupes;
Run Code Online (Sandbox Code Playgroud)