http://www.perlmonks.org?node_id=305755


in reply to Re^2: Find common prefix from a list of strings
in thread Find common prefix from a list of strings

sub maxprefix { my $p = quotemeta shift; for (@_) { chop $p until /^$p/ } return $p; }

This will still often fail on metacharacters because you'll get a "trailing \ in regexp" error.

sub maxprefix { my $p = shift(@_); for(@_) { chop $p until /^\Q$p/ } return $p; }

Update: The one you added has problems as well:

sub maxprefix { my $s = reverse shift; my $p = ''; for (@_) { $p .= quotemeta chop $s while /^$p/ } chop $p; return $p; }

It will find the maximum prefix between the first string and the string of the others that has the longest common prefix with the first string:

print maxprefix("testing","terse","tester","time"),$/;
prints test not t.

                - tye

Replies are listed 'Best First'.
Re^4: Find common prefix from a list of strings (trailing \)
by Aristotle (Chancellor) on Nov 10, 2003 at 00:11 UTC
    Fixed before I saw your note. :) quotemeta shift was a duh moment of course. Update: I must have left my brain in the shop today.

    Makeshifts last the longest.