按值搜索数组中的哈希值
我有一个函数可以将 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 美元等。
我将如何实施这样的搜索工具?
谢谢大家,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
借助 grep 的强大功能,
如果您知道只会返回一项,您可以这样做这个:(
未经测试,我有一段时间没有写其中一个,但这应该可行)
With the power of grep
If you know there will be only one item returned you can just do this:
(Untested, and I haven't written one of these in a while, but this should work)
如果您确定搜索始终只返回一次出现,或者您只对第一个匹配项感兴趣,那么您可以使用 List::Util
我将子例程调用包含在 %{ } 阻止以确保 RHS 计算为哈希值。
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
I enclosed the subroutine call in the %{ } block to ensure that the RHS evaluates to a hash.