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