Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

12. Regular Expressions > Alternations

Alternations

Always use character classes instead of single-character alternations.

Individually testing for single character alternatives:

if ($cmd !~ m{\A (?: a | d | i | q | r | w | x ) \z}xms) {
    carp "Unknown command: $cmd";
    next COMMAND;
}

may make your regex slightly more readable. But that gain isn't sufficient to compensate for the heavy performance penalty this approach imposes. Furthermore, the cost of testing separate alternatives this way increases linearly with the number of alternatives to be tested.

The equivalent character class:

if ($cmd !~ m{\A [adiqrwx] \z}xms) {
    carp "Unknown command: $cmd";
    next COMMAND;}

does exactly the same job, but 10 times faster. And it costs the same no matter how many characters are later added to the set.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint