为什么我在第一个 reduce 示例中得到错误的结果?
测试.txt
__BE
bb bbbbbbbbbbbbbbb
aaaaaa
测试.pl
#!/usr/bin/env perl
use warnings; use 5.012;
use open ':encoding(UTF-8)';
use List::Util qw(reduce);
use Encode;
my( @list, $longest, $len );
open my $fh, '<', 'test.txt' or die $!;
while( my $line = readline( $fh ) ) {
chomp $line;
push @list, split( /\s+/, $line );
}
close $fh;
$longest = reduce{ length($a) > length($b) ? $a : $b } @list;
$len = length $longest;
say $longest; # aaaaaa
say $len; # 6
$longest = reduce{ length(Encode::encode_utf8($a)) > length(Encode::encode_utf8($b)) ? $a : $b } @list;
$len = length(Encode::encode_utf8($longest));
say $longest; # bbbbbbbbbbbbbbb
say $len; # 15
$longest = $list[0];
$len = length $longest;
for my $str (@list) {
if ( length($str) > $len ) {
$longest = $str;
$len = length($str);
}
}
say $longest; # bbbbbbbbbbbbbbb
say $len; # 15