in reply to Print left-anchored similarities between two strings

String-xor (well, rather ^) to the rescue:

my @strings = qw( /home/usernames/doejohnwilson /home/usernames/doejanemary ); my $common = $strings[0] ^ $strings[1]; # every \x00 means the chars a +re identical my $common_length = 0; if ($common =~ /^(\x00+)/) { $common_length = length $1; }; print substr $strings[0], 0, $common_length;

Replies are listed 'Best First'.
Re^2: Print left-anchored similarities between two strings
by Anonymous Monk on Nov 10, 2009 at 17:22 UTC

    You can save a couple of steps:

    my @strings = qw( /home/usernames/doejohnwilson x/home/usernames/doejanemary ); my $common_length = ( $strings[0] ^ $strings[1] ) =~ /^\0*/ && $+[0]; print substr $strings[0], 0, $common_length;
      Awesome!

      I think this will work for me (since I can have an unspecified number of elements in an array...)

      # our $input is user inputted string # and I only want directory/ names our @matches = map { -d $_? $_ .="/" : "" } <$input*>; expand_match || print "\a"; sub expand_match { return $input = $matches[0] if(@matches == 1); # Get the longest matching string from all elements my $match = $matches[0]; for (@matches) { $match = substr $_, 0, ( $match ^ $_ ) =~ /^\0*/ && $+[0]; } return $input = $match if length($match) > length($input); return 0; }
Re^2: Print left-anchored similarities between two strings
by Anonymous Monk on Nov 11, 2009 at 00:27 UTC
    perldoc -f rindex
    my @strings = qw( /home/usernames/doejohnwilson /home/usernames/doejanemary ); my $common = $strings[0] ^ $strings[1]; print substr $strings[0], 0, rindex($common,"\x00"); __END__

      Careful. There can be matching characters after the first non-matching character!


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.