Longest Common Prefix in perl

I can’t help finding this slightly elegant. Unfortunately I no longer remember where the idea came from.

#!/usr/bin/perl
use strict;
use warnings;
sub longest_common_prefix {
    my $prefix = shift;
    for (@_) {
	chop $prefix while (! /^$prefix/);
    }
    return $prefix;
}
print longest_common_prefix(@ARGV), "
";

Comments

One response to “Longest Common Prefix in perl”

  1. Kjetil T. avatar
    Kjetil T.

    excellent, thanks a lot!

    you should enclose $prefix in Q E to handle any embedded regexp metacharacters, though.

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)