您可以使用哈希来跟踪迭代值时看到的最低成本
#!/usr/bin/perl
use strict;
use warnings;
my $aref = [
'ups_standard_international|23.63',
'ups_worldwide_saver|20.8',
'ups_worldwide_express|21.11',
'ups_worldwide_expedited|18.75',
'usps_first_class_package_international|33.43',
'usps_priority_mail_international|42.34',
'usps_priority_mail_express_international|61.79'
];
my %lowest;
foreach (@$aref) {
my ( undef, $cost ) = split /[|]/;
if ( !%lowest || $cost < $lowest{cost} ) {
$lowest{cost} = $cost;
$lowest{line} = $_;
}
}
print $lowest{line}, "\n";
编辑:我可能误解了 OP 的问题。
如果问题中“json”的sn-p不是Perl对象,而是一个原始的JSON字符串,我们可以使用JSON模块来做基本相同的事情,这里是上面代码的更新版本:
#!/usr/bin/perl
use strict;
use warnings;
use JSON qw(decode_json);
my $json = <<'END_JSON';
[
'ups_standard_international|23.63',
'ups_worldwide_saver|20.8',
'ups_worldwide_express|21.11',
'ups_worldwide_expedited|18.75',
'usps_first_class_package_international|33.43',
'usps_priority_mail_international|42.34',
'usps_priority_mail_express_international|61.79'
]
END_JSON
# First, use double quotes to quote the strings above, to make it valid JSON:
$json =~ s/^(\s*)'([^']+)'(,?)\s*$/$1"$2"$3/gms;
# Now decode the JSON above into a perl array
my @array = @{ decode_json($json) };
# This hash will hold the element with the lowest cost
my %lowest;
# While the array still has elements, take one line from it
while ( my $line = shift @array ) {
# Extract the cost from the line
my ( undef, $cost ) = split /[|]/, $line, 2;
# If this cost is the lowest we've seen yet, put it in the %lowest hash
if ( !%lowest || $cost < $lowest{cost} ) {
$lowest{cost} = $cost;
$lowest{line} = $line;
}
}
print $lowest{line}, "\n";