Table of Contents

Replacing with what was found

s/\bus(\W)/them\1/g;

We start with capturing whatever the \W matches, using parens. Then, we add it to the replacement string. The capture is of course in $1 , but as it is in a regex we refer to it as \1 .

The final problem is of course capitalising the replacement string when appropriate. Which in old versions of the tutorial I left as an exercise to the reader, having run out of motivation. A reader by the name of Paul Trafford duly solved the problem, and I have just inserted his excellent explanation for the elucidation of all concerned:

#         Solution to the us/them problem...
#
#   The program works through the text assigning the 
#   variable $1 to 'U' or 'u' for any words where this 
#   letter is followed by 's' and then by non 'word' 
#   characters.   The latter is assigned to variable $2.
#
#   For each such matching occurrence, $1 is replaced by 
#   the letter that precedes it in the alphabet using 
#   operations 'ord' and 'chr' that return the ASCII value 
#   of a character and the character corresponding to a 
#   given natural number.  After this 'hem' is tacked on 
#   followed by $2, to retain the shape of the original 
#   sentence.  The '/e' switch is used for evaluation.
#
#   NOTES
#   1. This solution will not replace US (short for 
#   United States) with Them or them.
#
#   2. If a 'magical' decrement operator '--' existed for 
#   strings then the solution could be simplified for we 
#   wouldn't need to use the 'chr' and 'ord' operators.
$_='Us ? The bus usually waits for us, unless the driver forgets us.';

print "$_\n";

s/\b([Uu])s(\W)/chr(ord($1)-1).hem.$2/eg;

print "$_\n";
   

An excellent solution, thanks Paul.

There are several more constructs. We'll take a quick look at \d which means anything that is a digit, that is 0-9 . First we'll use the negated form, \D , which is anything except 0-9 :

print "Enter a number :";
chop ($input=<STDIN>);

if ($input=~/\D/) {
        print "Not a number !!!!\n";
} else {
        print 'Your answer is ',$input x 3,"\n";

}

this checks that there are no non-number characters in $x . It's not perfect because it'll choke on decimal points, but it's just an example. Writing your own number-checker is actually quite difficult, but it is an interesting exercise. Try it, and see how accurate yours is.