CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Case Insensitive

 



waherne
Novice

Jan 22, 2001, 5:03 AM

Post #1 of 4 (465 views)
Case Insensitive Can't Post

Hi,

Can you make this if statement case insensitive?

$a ="ONE";
$b="One";

if($a eq $b){print "great, it now works and ignores case";}

Willie



BigRich
Novice

Jan 22, 2001, 5:31 AM

Post #2 of 4 (464 views)
Re: Case Insensitive [In reply to] Can't Post

$a ="ONE";
$b="One";

compare lower case:
if(lc($a) eq lc($b)){print "great, it now works and ignores case";}

compare upper case:
if(uc($a) eq uc($b)){print "great, it now works and ignores case";}

case insensitive regex
if ($a =~ /^$b$/i) {print "great, it now works and ignores case";}



BigRich




waherne
Novice

Jan 22, 2001, 6:33 AM

Post #3 of 4 (463 views)
Re: Case Insensitive [In reply to] Can't Post

Thanks Big Rich,

That's exactly what I needed.

The third option looks the most efficient. Do you know if it would execute the print statement if $a="ON" or $b="On". The / / give me the impression that it could happen, I think it's called pattern matching.

Thanks again,

Willie



japhy
Enthusiast

Jan 22, 2001, 7:09 AM

Post #4 of 4 (462 views)
Re: Case Insensitive [In reply to] Can't Post

No no no no no. The third is not the most efficient, and the third has a subtle bug (and a not-so-subtle bug).


Code
$a = "abcdef\n"; 
$b = "abc.ef";

if ($a =~ /^$b$/i) {
print "$a and $b are identical, except for case.\n";
}

This shows the two bugs. First, the $ anchor in a regex can match IMMEDIATELY before a newline at the end of a string, and using a variable in a regex allows it to be seen as containing regex characters. To make the regex proper and safe, you must do:


Code
$a =~ /^\Q$b\E\z/i

Ick. Come on. String matching is not pattern matching. You want to compare strings, not a string and a pattern. Use one of the first two examples given:


Code
if (uc($a) eq uc($b)) { ... } 
if (lc($a) eq lc($b)) { ... }

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives