Node:Pattern Matching, Next:Regular Expression Shortcuts, Previous:The Simple, Up:Regular Expressions
Now that you are familiar with some of the basics of regular
expressions, you probably want to know how to use them in Perl. Doing
so is very easy. There is an operator, =~
, that you can use to
match a regular expression against scalar variables. Regular
expressions in Perl are placed between two forward slashes (i.e.,
//
). The whole $scalar =~ //
expression will evaluate to
1
if a match occurs, and undef
if it does not.
Consider the following code sample:
use strict; while ( defined($currentLine = <STDIN>) ) { if ($currentLine =~ /^(J|R)MS speaks:/) { print $currentLine; } }
This code will go through each line of the input, and print only those lines that start with "JMS speaks:" or "RMS speaks:".