in reply to Difference Of Two Strings

I tried to come up with a solution using tr/// since its much faster, but had to bring in the s/// operator instead...
#!/usr/bin/perl -wT use strict; no warnings "uninitialized"; # printing undef triggers a stupid warni +ng # testing loop for my $pair (['aabbcc', 'abc'], ['aabbccdd', 'abcdd'], ['abc', 'abc'], ['abc', '123'], ) { my $left = leftover(@$pair); printf ("%8s - %-6s => %-5s\n",@$pair,"'$left'"); } # scrabble "subtraction" subroutine sub leftover { my $string = shift; my $letters = shift; $string =~ s/$_// || return for split // => $letters; return $string; } =OUTPUT aabbcc - abc => 'abc' aabbccdd - abcdd => 'abc' abc - abc => '' abc - 123 => ''
You'll have to be careful in your usage of this sub, since your specs state nearly opposite meanings for the return values of '' and undef.

Update: added || return to test for unmatched chars.

-Blake

Replies are listed 'Best First'.
Re: Re: Difference Of Two Strings
by YuckFoo (Abbot) on Nov 03, 2001 at 05:05 UTC
    Thanks for the new approach, I hadn't tried this one. Unfortunately it's quite a bit slower, and doesn't check for characters in the second string not matched in the first.

    leftover: 16 wallclock secs (15.80 usr + 0.00 sys = 15.80 CPU) @ 6481.01/s (n=102400)
    l_blakem: 26 wallclock secs (26.07 usr + 0.00 sys = 26.07 CPU) @ 3927.89/s (n=102400)

      I updated it slightly to check for the extra chars....

      -Blake