Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^3: Find common prefix from a list of strings (trailing \)

by tye (Sage)
on Nov 10, 2003 at 00:09 UTC ( #305755=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://305755]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2020-01-21 23:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?