Search for hash in an array by value

旧街凉风 提交于 2020-01-01 10:06:14

问题


I have a function which extracts Excel data into an array of hashes like so:


sub set_exceldata {

    my $excel_file_or = '.\Excel\ORDERS.csv';
    if (-e $excel_file_or) {

        open (EXCEL_OR, $excel_file_or) || die("\n can't open $excel_file_or: $!\n");                   
        while () {

            chomp;
            my ( $id, $date, $product, $batchid, $address, $cost ) = split ",";
            my %a = ( id      => $id
                    , date    => $date
                    , product => $product
                    , batchid => $batchid
                    , address => $address
                    , cost    => $cost
                    );
            push ( @array_data_or, \%a );
        }
        close EXCEL_OR;
    }
}

Populating the array of hashes is fine. However, the difficult part is searching for a particular item (hash) in the array. I can't seem to locate items that might have an id or 21, or a batchid of 15, or a cost > $20 etc.

How would I go about implementing such a search facility?

Thanks to all,


回答1:


With the power of grep

my @matching_items = grep {
  $_->{id} == 21
} @array_data_or;

If you know there will be only one item returned you can just do this:

my ($item) = grep {
  $_->{id} == 21
} @array_data_or;

(Untested, and I haven't written one of these in a while, but this should work)




回答2:


If you're sure that the search always returns only one occurence or if you're interested in only the first match then you could use the 'first' subroutine found in List::Util

use List::Util;

my %matching_hash = %{ first { $_->{id} == 21 } @array_data_or };

I enclosed the subroutine call in the %{ } block to ensure that the RHS evaluates to a hash.



来源:https://stackoverflow.com/questions/934225/search-for-hash-in-an-array-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!