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 *