Regular expression
Simple use of regular expression
If you want to find a string in a string, you use the regular expression (or regex).
The above example gives TRUE, if the string von is in the string $name. If Von is in the string, it is registered as FALSE. Regex is case sensitive. If you add the i option you make it case insensitive.$name =~ /von/
You can add meta-characters to make searching easy. You can use [] to search for a set of several characters. The next example search for Carl and Karl.$name =~ /von/i
You can also exclude characters. Let's say that you are not interested in Carla or Karla.$name =~ /[CK]arl/
The meta-character ^ has also another meaning. Say you are searching for a word that starts with j.$name =~ /[CK]arl[^a]/
$name =~ /^j/i
Example:
You also have the special variable $_. If you use this variable you don't have to use the =~.
print "What do you read before asking a question?"; chomp ($answer=<STDIN>); if ($answer =~ /faq/i) { print "Right! You're a perfect student! \n"; } else { print "Begone, vile creature! \n"; }
print "What do you read before asking a question?"; chomp ($_=<STDIN>); if (/faq/i) { print "Right! You're a perfect student! \n"; } else { print "Begone, vile creature! \n"; }Substitution
You can do more then just search, you can also replace. This is called substitution. You do this with s///. Between the slashes you place the to search and the replace strings. For example if you want to replace Eli with Tom:
You can also make substitution case insensitive with the i option.
$_="Eli is a really good teacher!"; print "$_\n"; s/Eli/Tom/; print "$_\n";Normally a substitution will only happens once. If you want it to happen more as once, you have to add the g option.
$_="Eli is a really good teacher!"; print "$_\n"; s/eli/Tom/i; print "$_\n";
$_="Eli is a really good teacher! Eli is the best!"; print "$_\n"; s/eli/Tom/ig; print "$_\n";Split and Join
The split function exists of 2 parts. The first part tells where it should be split. The second part tells which string should be split.
If you use the special variable $_ for the to split string, you can make it a lot shorter.
$line="Tom;Bert;Frank;Eli;Brigitte"; print "$line \n"; @fields = split (/;/, $line); foreach $field(@fields) { print "$field \n"; }
$line="Tom;Bert;Frank;Eli;Brigitte"; print "$_ \n"; @fields = split (/;/); foreach (@fields) { print "$_ \n"; }You also have the join function. With join you put the pieces back together. The join function exists of 2 parts. The first part is the "glue" operator, the operator needed to separate the parts. The second part has the different strings that need to glued.
$name1="Tom"; $name2="Bert"; $name3="Frank"; $name4="Eli"; $name5="Brigitte"; $fields = join(";", $name1, $name2, $name3, $name4, $name5); print "$fields";