Part of what makes Perl such a useful language is its powerful string-matching
and handling capabilities. Regular expressions are basically patterns a
programmer can compare a string of text to. Matching a regular expression with
a string of text either returns true or false. The two main pattern matching
operators are
m// and
s//. These are the matching and
substitution operators respectively. Another function that makes use of regular
expressions is
split
The matching operator
m// is normally written //.
Perl allows you to change the delimiters to something besides /. If you don't
change the delimiters from /, you can use // instead of m//.
Now for a quick example of m//:
while(<>){
if(/the/){ #does $_ contain the
print "Your line of text contains the word 'the'\n";
}
}
Now for a quick example of
s///:
@machines_os=("OpenBSD","Windows","Linux", "Windows");
foreach(@machines_os){
s/Windows/Linux/;
}
This function goes through each of the items in @machine_os. If any of
them contain Windows, the thing between the first set of //. It is replaced with
Linux the string between the second and third /'s. You can see why you've gotta love Perl. Instead of
1 OpenBSD machine, 2 Windows machines and a Linux box, I now have 1 OpenBSD box
and 3 Linux machines. At least that is what @machines_os now contains.
Now on to
Quantifiers in regular expressions.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.