Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Find common prefix from a list of strings

by bobn (Chaplain)
on Jul 14, 2003 at 19:43 UTC ( #274130=note: print w/replies, xml ) Need Help??

in reply to Find common prefix from a list of strings

die is not the way to normally end execution. And for can iterate a list without indexing.

my $posn = -1; my $same = 1; while(defined $same and $posn <= length $files[0]){ my $chr = substr($files[0], ++$posn, 1); for my $name (@files) { undef $same and last if(substr($name, $posn, 1) ne $chr or length $name < $posn); } } print 'Prefix is "', substr($files[0], 0, $posn), '"';
But I can't help but think there's a better way, such as:
# UNTESTED $max = ( sort { $a <=> $b } map { length } @files )[0]; # length of smallest filename - I hope. LIST: for $len ( 1..$max) ) { $s = substr($file[0],0,$len); last LIST unless scalar grep { /^$s/ } @files == @files; # precedence issue here? } print "prefix: '",substr($file[0],1,$len-1), "'\n";

Update: added line to get min length of any filename.

--Bob Niederman,

Replies are listed 'Best First'.
Re: Re: Find common prefix from a list of strings
by Albannach (Prior) on Jul 14, 2003 at 19:58 UTC
    Drat! Thanks for the reality check - the die was just there for testing, I should have taken it out as it does not add anything, similarly the for was a hold over from an earlier attempt. I've got to proof read my posts more!

    You obviously have the same must-be-a-better-way (MBABW?) feeling, and I like the idea of the grep trick, though I must admit I usually have a fear of labels. Anyway your code will work with a few minor fixes:

    my $s; LIST: for my $len ( 1..length $files[0]) { $s = substr($files[0],0,$len - 1); last LIST unless (scalar grep { /^$s/ } @files) == @files; } chop $s; print "prefix: $s\n";
    Update: Not silly at all bobn, I should really have specified that an empty string is the correct answer for no common prefix - thanks for pointing that out.

    I'd like to be able to assign to an luser

      Actually, there's one other "bug" - if there are never any matches, I will print out that the prefix is '' - well actually, as a zero-length string, that's actually not untrue, but still silly.

      --Bob Niederman,
      Loved your chop $s; - it's the easiest and coolest way to deal with the "I found the condition that makes me stop, but i already added one too many characters" - in fact, I've used it that way myself.

      --Bob Niederman,

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2020-01-20 23:21 GMT
Find Nodes?
    Voting Booth?