Ok, now that you know some of the basics i can start to talk about useful things. This chapter is going to cover regular expressions.
Regular expressions are the most useful thing in perl, very powerful for data processing, theyre really the whole reason why im even writing this guide.
First type of regular expression: Matching
Regular expressions are enclosed in / signs.
$var =~ m/expr/; will return true if $var matches expr. Now, for some talk on how to craft “expr”
Character matches:
* – matches any character.
\w – matches whitespace character
\d – matches digits
Quantifiers:
-These specify how many times a character is going to be matched if you dont use one it will match it exactly 1 time.
. – any ammount of times
[n,m] – between n and m times
? – 0 or 1 times
Example:
$var =~ m/.*\d\d.*/;
will return true when it finds two digits somewhere in a string.
Useing matching to pull out data:
If you want to pull out characters according to a regular expression you encase the specified form in ( ) signs and you use the my() command.
my($age) = $ages =~ m/His age is: ([1,3]\d)/;
This line will fill the variable $age with the digits left in that form. We specified them as a digit between 1 and 3 characters.
Subsitutions:
if you want to subsitute all the characters of a specified type in some variable with another character you use subsitutions:
$string =~ s/a/A;
This changes all the lowercase a’s to captial A’s
Translations:
Translations are like substitutions only they work for a string, not just a single character. It allows you to substitute one string for another. Translations will only happen once per variable. so if there are multiple things in the same variable that need to be translated you are going to need to break that string up accordingly.
$string =~ tr/mike/Bob/;
if there is one mike in $string it will translate it to Bob. If there was more than one mike and you want them all translated your going to have to break the string up or hit it multiple times with the translation.