Search for a hash in an array by value

I have a function that extracts Excel data into an array of hashes, for example:


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;
    }
}

Filling the hash array is fine. However, the hard part is finding a specific item (hash) in the array. I can not find items that can have an identifier of either 21, or a pack of 15, or a cost> $ 20, etc.

How can I implement such a search object?

Thanks everyone

+5
source share
2 answers

With power grep

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

If you know that there will be only one returned item, you can simply do this:

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

(Unverified, and I did not write any of them after a while, but this should work)

+18

, , , "" , :: Util

use List::Util;

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

% {}, , RHS .

+5

All Articles