Given a list of strings as the arguments, returns the initial substring (aka prefix) common to all of them.

With a trivial modification (use -$i instead of 0, $i in all of the substr calls), this could also be used to find the common terminal substring (suffix).

sub cis { my $first = shift; my $i = length $first; for (@_) { if ((substr $_, 0, $i) eq (substr $first, 0, $i)) {next} else {$i--; redo} } substr $first, 0, $i; }

Replies are listed 'Best First'.
Re: Find the common initial substring (prefix if you insist)
by stefp (Vicar) on Sep 20, 2001 at 02:39 UTC
    For regexps abusers, with the added condition of no null character in parameter strings:

     sub cis { (join( "\0", @_) =~ m/^([^\0]*)[^\0]*(\0\1[^\0]*)*$/)[0] } Thanks to ChemBoy for pointing an omission and compacting into one statement.

    -- stefp