开发者

longest_string in CPAN?

This SO page shows how to find the longest string in an array.

I开发者_Go百科s this functionality available in a CPAN module as something like 'longest_string' for example? Seems odd to have to duplicate that bit of code. Also seems like a generally useful sub.

For comparison, here's an SO page discussing how to do this in Python.


I suspect you'll find that CPAN is more for substantial pieces of code (i.e., more than one-liners).

I, for one, would prefer to have CPAN solve my big problems, like database access or various numerical methods and data structures.


I disagree. Finding the longest string is trivial to implement and not that often needed. If anything, a more general function could probably make its way into (I suppose) List::MoreUtils. Like this:

my $longest = find_max { length } @array;

where find_max has a (&@) prototype and implements the algorithm from the linked post.


FWIW the Perl 6 solutions is simply:

my $longest = @list_of_strings.max: *.chars

No module necessary :-)


Note the description of List::MoreUtils:

List::MoreUtils provides some trivial but commonly needed functionality on lists which is not going to go into List::Util.

The minmax sub in List::MoreUtils will work but compare numerical values, instead of string lengths. However, minmax can be adapted quite easily to instead compare the lengths of its arguments.

sub minmax_stringlength (@) {
    return unless @_;
    my $min = my $max = $_[0];

    for ( my $i = 1; $i < @_; $i += 2 ) {
        if ( length($_[$i-1]) <= length($_[$i]) ) {
            $min = $_[$i-1] if length($min) > length($_[$i-1]);
            $max = $_[$i]   if length($max) < length($_[$i]);
        } else {
            $min = $_[$i]   if length($min) > length($_[$i]);
            $max = $_[$i-1] if length($max) < length($_[$i-1]);
        }
    }

    if ( @_ & 1 ) {
        my $i = $#_;
        if (length($_[$i-1]) <= length($_[$i])) {
            $min = $_[$i-1] if length($min) > length($_[$i-1]);
            $max = $_[$i]   if length($max) < length($_[$i]);
        } else {
            $min = $_[$i]   if length($min) > length($_[$i]);
            $max = $_[$i-1] if length($max) < length($_[$i-1]);
        }
    }

    return ($min, $max);
}

Note, I did not write the above, I merely added length in the comparisons where before the mere number was being compared. Unfortunately I could not test this because I do not know how the AutoLoader works and I kept getting:

Use of inherited AUTOLOAD for non-method List::MoreUtils::minmax_stringlength() is deprecated at script.pl line 9.

So if the OP finds himself using find max very often he could just exercise his license and modify MoreUtils to provide that functionality.

If somebody more knowledgeable could verify that the above would work please do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜