Table of Contents

Senstivity -- regexes in touch with their inner child

But what if someone enters 'The FAQ' ? It fails, because the regex is case sensitive. We can easily fix that:

if (/the faq/i) {

with the /i switch, which specifies case-insensitivity. Now it works for all variations, such as "the Faq" and "the FAQ".

Now you can appreciate why a regular expression is better in this situation than a simple test using eq . As the regex searches one string for another string, a response of "I would read the FAQ first !" will also work, because "the FAQ" will match the regex.

Study this example just to clarify the above. Tabs and spaces have been added for aesthetic beauty:

$_="perl for Win32";                            # sets the string to be searched

if ($_=~/perl/) { print "Found perl\n" };       # is 'perl' inside $_ ?  $_ is "perl for Win32".
if (/perl/)     { print "Found perl\n" };       # same as the regex above.  Don't need the =~ as we are testing $_
if (/PeRl/)     { print "Found PeRl\n" };       # this will fail because of case sensitivity
if (/er/)       { print "Found er\n" };         # this will work, because there is an 'er' in 'perl'
if (/n3/)       { print "Found n3\n" };         # this will work, because there is an 'n3' in 'Win32'
if (/win32/)    { print "Found win32\n" };      # this will fail because of case sensitivity
if (/win32/i)   { print "Found win32 (i)\n" };  # this will *work* because of case insensitivity (note the /i)

print "Found!\n"  if      / /;                  # another way of doing it, this time looking for a space

print "Found!!\n" unless $_!~/ /;		# both these are the same, but reversing the logic with unless and !
print "Found!!\n" unless    !/ /;		# don't do this, it will always never not confuse nobody :-)
						# the ~ stays the same, but = is changed to ! (negation)

$find=32;                                       # Create some variables to search for
$find2=" for ";                                 # some spaces in the variable too

if (/$find/)  { print "Found '$find'\n" };      # you can search for variables like numbers
if (/$find2/) { print "Found '$find2'\n" };     # and of course strings !

print "Found $find2\n" if /$find2/;           # different way to do the above

As you can see from the last example, you can embed a variable in the regex too. Regular expressions could fill entire books (and they have done, see the book critiques at http://www.perl.com/) but here are some useful tricks: