cst*_*mas 1 perl operators subroutine
我有一个名为"lookup"的子程序,它在给定值的哈希中执行查找.我意识到如果我可以要求它看不到给定的值,而是小于作为参数传递的值,那将会更强大.
我可以使lookupbigger,lookupsmall等等,但我相信有更好的方法.
# lookup id according to the search criteria
sub lookup {
my( $data, $lk, $lv ) = ( @_ );
my @res;
foreach my $key (keys $data) {
my $value = $$data{$key};
next unless( defined $$value{$lk} );
# this is the line where I want to replace eq with another operator
push(@res, $key) if( $$value{$lk} eq $lv );
}
return \@res;
}
Run Code Online (Sandbox Code Playgroud)
您可以将标准函数传递给查找函数:
#!/usr/bin/env perl
use strict; use warnings;
use YAML;
my %hash = qw(a 1 b 2 c 3 d 4 e 5);
# find all keys with odd values
print Dump lookup_keys_by_value(\%hash, sub {
return unless @_;
my $v = shift;
return $v % 2;
},
);
sub lookup_keys_by_value {
my ($hash, $criterion) = @_;
my @keys;
while (my ($k, $v) = each %$hash) {
push @keys, $k if $criterion->($v);
}
return \@keys;
}
Run Code Online (Sandbox Code Playgroud)