http://www.perlmonks.org?node_id=274134


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

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

Replies are listed 'Best First'.
Re: Re: Re: Find common prefix from a list of strings
by bobn (Chaplain) on Jul 14, 2003 at 20:05 UTC
    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, http://bob-n.com
Re: Re: Re: Find common prefix from a list of strings
by bobn (Chaplain) on Jul 14, 2003 at 20:08 UTC
    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, http://bob-n.com