Skip to content

Instantly share code, notes, and snippets.

@boopsie
Created August 9, 2012 23:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boopsie/3309172 to your computer and use it in GitHub Desktop.
Save boopsie/3309172 to your computer and use it in GitHub Desktop.
Perl Longest Common Prefix
# returns longest common prefix of a list of strings
sub lcp
{
my $match = shift;
substr($match, (($match ^ $_) =~ /^\0*/, $+[0])) = '' for @_;
$match;
}
@CS-cwhite
Copy link

Two things:

  1. WOW!!! :)
  2. What is the license for this code?

Thanks!

My own analysis, for anyone who is curious ---

  • ($match ^ $_) =~ /^\0*/ matches the run of prefix characters in common between $match and $_ (string XOR produces null == \0 where characters match).
  • $+[0] is the offset of the end of that run.
  • substr() = '' removes the part of $match starting at the leftmost char position that differs between $match and $_.
  • for @_ loops over all strings except the first (which was handled by the initial shift), removing the mismatched suffix each time.

@lubwen
Copy link

lubwen commented Nov 10, 2022

Is there a version to return the longest common suffix of a list of strings?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment