Table of Contents

Character Classes

@names=qw(Karlson Carleon Karla Carla Karin Carina Needanotherword);

foreach (@names) {                      # sets each element of @names to $_ in turn
        if (/[KC]arl/) {                # this line will be changed a few times in the examples below
                print "Match !  $_\n";
        } else {
                print "Sorry.   $_\n";

This time @names is initialised using whitespace as a delimiter instead of a comma. qw refers to 'quote words', which means split the list by words. A word ends with whitespace (like tabs, spaces, newlines etc).

The square brackets enclose single characters to be matched. Here either Karl or Carl must be in each element. It doesn't have to be two characters, and you can use more than one set. Change Line 4 in the above program to:

if (/[KCZ]arl[sa]/) {

matches if something begins with K, C, or Z, then arl, then either s or a. It does not match KCZarl. Negation is possible too, so try this :

if (/[KCZ]arl[^sa]/) {

which returns things beginning with K, C or Z, then arl, and then anything EXCEPT s or a. The caret ^ has to be the first character, otherwise it doesn't work as the negation. Having said [ ] defines single characters only, I should mention than these two are the same:


if you use a hyphen then you get the list of characters including the start and finish characters. And if you want to match a special character (metacharacter), you must escape it:


matches Karl or -arl. Although the - character is represented by two characters, it is just the one character to match.