8

我有一个函数可以将 Excel 数据提取到一个哈希数组中,如下所示:


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

填充哈希数组很好。但是,困难的部分是在数组中搜索特定项目(哈希)。我似乎无法找到可能具有 id 或 21、batchid 为 15 或成本 > 20 美元等的项目。

我将如何实施这样的搜索工具?

谢谢大家,

4

2 回答 2

22

借助grep的力量

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

如果您知道只会退回一件商品,您可以这样做:

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

(未经测试,我已经有一段时间没有写其中之一了,但这应该可以)

于 2009-06-01T10:24:28.360 回答
5

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.

于 2009-06-01T12:33:14.450 回答