Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two strings regardless of case size in perl

is there anyway to compare two strings regardless of case size? For Example

"steve" eq "STevE"   <----- these would match
"SHOE" eq "shoe"

You get the picture

like image 551
shinjuo Avatar asked Aug 03 '10 17:08

shinjuo


People also ask

How do you compare strings in regardless of case?

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.

How do I compare strings in Perl with case insensitive?

Perl's string comparison is case-sensitive. If you want a case insensitive string comparison, use the lc function to convert the strings to lowercase beforehand.

How do you compare two string cases insensitive?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. toUpperCase() function: The str.

What does =~ mean in Perl?

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {


2 Answers

yes - use uc() (upper-case function; see http://perldoc.perl.org/functions/uc.html )

$ perl -e 'print uc("steve") eq uc("STevE"); print "\n";'
1
$ perl -e 'print uc("SHOE") eq uc("shoe"); print "\n";'          
1
$ perl5.8 -e 'print uc("SHOE") eq uc("shoe1"); print "\n";'

$

You can obviously use lc() as well.

If you want the actual "eq" operator to be case insensitive, it might be possible using overloads but I don't think that's what you are asking for - please clarify your question if that's the case. Nor is it a great idea if you do want that, IMHO - too fragile and leads to major possible hard to trace and debug bugs.

Also, it's an overkill in your specific case where you just want equality, but Perl regular expressions also have case-independent modifyer "i"

like image 92
DVK Avatar answered Oct 13 '22 22:10

DVK


A couple of ways to do this:

  • Use the lc or uc operator, which converts both strings to lower or upper case respectively:

    lc "steve" eq lc "STevE";
    
  • A simple regex will do just as well:

    'steve' =~ /^STevE$/i;
    
like image 28
Zaid Avatar answered Oct 13 '22 23:10

Zaid