通过数值数组搜索哈希 [英] Search for hash in an array by value
本文介绍了通过数值数组搜索哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有提取Excel数据导入哈希的这样一个数组的函数:
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;
}
}
填充散列数组是罚款。然而,困难的部分是搜索的阵列中的特定项(散列)。我似乎无法找到,可能有一个id或21,或15 batchid或成本>港币$ 160等项目
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?
感谢所有,
推荐答案
随着的grep 电源p>
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)
这篇关于通过数值数组搜索哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文