Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to locate the first not equal character in two strings

Data manipulation

How to locate the first not equal character in two strings

by  prex1  Posted    (Edited  )
The sub requires two strings as the input and returns:
-1 if the strings are equal or both returning false when used in a boolean op (e.g. undef or length zero or '0', but not '00')
0 if one string is false (as above) and not the other one
the position of the first different character (0 if the first character is not equal, 1 if the second,etc)
Code:
sub first_nomatch{
  my($sa,$sb)=@_;
  return -1 unless $sa || $sb;
  return 0 unless $sa && $sb;
  return 0 if ord($sa) != ord($sb);
  return -1 if $sa eq $sb;
  my$sc="$sa" ^ "$sb";
  $sc=~/^(\x00+)/;
  return length($1);
}
The double quotes in the 7th line are required only if the strings might ever be passed to the sub as numbers.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top