Longest Common Prefix in perl

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

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

One response

  1. Kjetil T. avatar
    Kjetil T.

    excellent, thanks a lot!

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