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), "
";

Tags:

One Response to “Longest Common Prefix in perl”

  1. Kjetil T. Says:

    excellent, thanks a lot!

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

Leave a Reply

You must be logged in to post a comment.