×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Data manipulation

How to locate the first not equal character in two strings by prex1
Posted: 8 Oct 07 (Edited 17 Oct 07)

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.

Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close