Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by ysth (Canon)
on Nov 10, 2003 at 03:00 UTC ( #305776=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

That approach is quite nice. Here's a unsightly twist on it:
#!/usr/bin/perl -wl use strict; use warnings; sub Prefix { my $p = shift; ($p)=$_=~join'','\A',map("(\Q$_",split//,$p),join'?',(')')x length( +$p)or return'' for @_; $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
but I prefer the chop.

Replies are listed 'Best First'.
Re^4: Find common prefix from a list of strings
by slink (Initiate) on Feb 22, 2014 at 11:57 UTC

    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
      You can also just add '^' as the second parameter to join in the previous answer.
      لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      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://305776]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2020-01-26 20:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?