
Kenosis
User
Mar 26, 2013, 6:38 PM
Post #2 of 4
(17411 views)
|
Re: [peol] Comparing two strings, ignoring a specific character
[In reply to]
|
Can't Post
|
|
One way would be to substitute the "*" with a "." and do a match, like the following:
print "Same\n" if $string =~ /^ABC.E\z/; You can see that the match is hard coded, so is not too helpful except to illustrate that the "." in a regex will match any char (almost :). However, the order of strings becomes a bit more complicated when comparing $comp and $comp2, since the latter has to be in // for the matching to succeed. All of this can be taken care of in a subroutine to which you send any two of these strings to do a comparison test using 'wild-card' characters:
use strict; use warnings; my $string = "ABCDE"; my $comp = "ABC*E"; my $comp2 = "*BC*E"; print "Same\n" if wildSame( $string, $comp ); print 'Same' if wildSame( $string, $comp2 ); sub wildSame { s/\*/./g for @_; my ( $var1, $var2 ); my $count1 = $_[0] =~ tr/.//; my $count2 = $_[1] =~ tr/.//; if ( $count1 < $count2 ) { $var1 = $_[0]; $var2 = $_[1]; } else { $var1 = $_[1]; $var2 = $_[0]; } return $var1 =~ /^$var2\z/; } Output: The subroutine first globally replaces any "*" with "." and then counts the number of "." in each of the two strings, so the one with more "." ends up in //. Hope this helps!
|