views:

113

answers:

2

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

+6  A: 

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"

DVK
This works great
shinjuo
+4  A: 

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;
Zaid
These work great
shinjuo
Reread the smartmatch docs; that last one is falling into the Any~~Regex case which means the left site is stringified and matched using the right. On 5.10.1, it appears to be doing `"(?i-xsm:steve)" =~ /STevE/i` when I would have expected `( $_ =~ /steve/i ) =~ /STevE/i`, but neither is appropriate here.
ysth
N.B. smartmatch on 5.10.0 has design flaws (that were fixed in 5.10.1) and shouldn't be used.
ysth
@ysth : Good point.
Zaid
maybe I made my comment too complicated. succinctly, the ~~ doesn't work for this. For instance, /steve/i ~~ /x/i is true.
ysth
You should anchor your regexp, `'steven' =~ /STevE/i;` will also be true.
Ven'Tatsu