in reply to Re: Comparing $_ --- before/after
in thread Comparing $_ --- before/after

Ok, let's simplify this.
$string1 = "abcdf"; $string2 = "abcde"; #how to display difference between $string2 and $string1? $difference = "f";

Replies are listed 'Best First'.
Re^3: Comparing $_ --- before/after
by zwon (Abbot) on Oct 10, 2009 at 10:37 UTC

    I'm not sure what do you call "difference". Can you give more strict definition? What is the difference between "Lazy dog" and "Loony owl"?

      Yes. In your example, script should display
      $difference = "oony owl";
      as only starting "L" match both strings.

        What about "o" in owl and dog? And what about backward difference? This is not exactly what String::Diff do. If you only want to get characters from second string which doesn't match to the characters in the first string it may be quite simple to implement, but I wouldn't call this a difference.

        Update: maybe you'll find the following (quick and dirty, sorry, I don't yet have my tea) code useful:

        use strict; use warnings; use 5.010; my $pair1 = ['abcdf', 'abcde']; my $pair2 = ['Lazy dog', 'Loony owl']; for my $ref ($pair1, $pair2) { say "Words: ", join ", ", @$ref; say "Diff: ", diff(@$ref); say "Diff (rev): ", diff(reverse @$ref); } sub diff { my ($str1, $str2) = @_; my @arr1 = split //, $str1; my @arr2 = split //, $str2; my @res = (); while ($_ = shift @arr2) { my $ch = shift @arr1 or last; push @res, $ch unless $ch eq $_; } push @res, @arr1; join "", @res; } __END__ Words: abcdf, abcde Diff: f Diff (rev): e Words: Lazy dog, Loony owl Diff: azy dg Diff (rev): oony wl
      Yes, true. I don't need all that code from String::Diff.
      I only want a simple way to display characters from second string which doesn't match to the characters in the first string.