Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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

by Albannach (Prior)
on Jul 14, 2003 at 19:58 UTC ( #274134=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

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