in reply to Find common prefix from a list of strings
First I AND together all the elements of the array (therefore only bits that are the same for all items are set), then I XOR the result with the first element to get zeroes for all characters that are the same, then strip everything from the first nonzero character and last get as many characters from the first element as you have zeroes.@files = qw(model4run1 model2run1 model4run2 model1run1); my $first = shift(@files); my $combined = $first; foreach (@files) { $combined &= $_; } $combined ^= $first; $combined =~ s/[^\x00].*//; my $prefix = substr($first, 0, length($combined)); print qq{Prefix is "$prefix"\n};
Update: You can of course replace the my $first = shift(@files); by my $first = $files[0];, the result will be the same and @files will be preserved.
Update: The code is wrong. It returns an incorrect result for
See a fixed version here. It makes my solution a little slower, but it's still the fastest.@files = qw(model4run1 model5run1);
Jenda
Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.
-- Rick Osborne
Edit by castaway: Closed small tag in signature
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Find common prefix from a list of strings
by fletcher_the_dog (Friar) on Jul 14, 2003 at 21:57 UTC | |
by Jenda (Abbot) on Jul 14, 2003 at 22:05 UTC | |
by antirice (Priest) on Jul 15, 2003 at 00:46 UTC | |
by Jenda (Abbot) on Jul 15, 2003 at 12:09 UTC | |
by fletcher_the_dog (Friar) on Jul 15, 2003 at 14:29 UTC |
In Section
Seekers of Perl Wisdom