In Perl, how can I find the index of a given value in an array?

前端 未结 7 1829
迷失自我
迷失自我 2020-12-01 11:15
$VAR1 = [
          \'830974\',
          \'722065\',
          \'722046\',
          \'716963\'
        ];

How can I calculate the array index for

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 12:00

    If you only need to look up the one item, use firstidx as others have said.

    If you need to do many lookups, build an index.

    If your array items are unique, building an index is quite simple. But it's not much more difficult to build one that handles duplicate items. Examples of both follow:

    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;
    

提交回复
热议问题