Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^4: Find common prefix from a list of strings

by slink (Initiate)
on Feb 22, 2014 at 11:57 UTC ( #1075819=note: print w/replies, xml ) Need Help??


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

I really liked the one-liner, just that it doesn't work - it fails for 000 720

Here's what I came up with. Is doesn't look that efficient, but it has the advantage of using no regexen for the actual comparison (only for split).
#!/usr/bin/perl -wl use strict; use warnings; sub Prefix { { my $e = scalar(@_); return '' if ($e == 0); return $_[0] if ($e == 1); } my $minlen; my @d = map { my @split = split(//, $_); my $l = scalar(@split); if (defined($minlen)) { $minlen = $l if ($l < $minlen); } else { $minlen = $l; } \@split; } @_; my $p = ''; my $i = 0; while($i < $minlen) { my $c = $d[0]->[$i]; return $p unless ($c); for (my $j = 1; $j <= $#d; $j++) { return $p unless ($c eq $d[$j]->[$i]); } $p .= $c; $i++; } $p } while (<DATA>) { print "$_=> ", Prefix(split ' ',$_); } __DATA__ model4run1 model2run1 model4run2 model1run1 model4run1 model2run1 model4run2 abbot model4run1 model2run1 abbot model1run1 model4run1 model2run1 model4run2 monk model4run1 model2run1 monk model1run1 testing terse testing time monk model4run1 model2run1 model1run1 000 720 a aa abc a aa a aa aaa ab ba bb

Replies are listed 'Best First'.
Re^5: Find common prefix from a list of strings
by choroba (Archbishop) on Feb 22, 2014 at 12:14 UTC
    You can also just add '^' as the second parameter to join in the previous answer.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^5: Find common prefix from a list of strings
by ysth (Canon) on Feb 23, 2014 at 04:03 UTC
    Thanks, fixed it (adding \A)
    --
    A math joke: r = | |csc(θ)|+|sec(θ)| |-| |csc(θ)|-|sec(θ)| |

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2019-12-13 02:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?