| Perl string matching |
|
|
|
| Saturday, 23 August 2008 18:13 | |||
Regular expressionsA regular expression is contained in slashes, and matching occurs with the =~ operator. The following expression is true if the string the appears in variable $sentence.$sentence =~ /the/The RE is case sensitive, so if $sentence = "The quick brown fox";then the above match will be false. The operator !~ is used for spotting a non-match. In the above example $sentence !~ /the/is true because the string the does not appear in $sentence.
The $_ special variableWe could use a conditional asif ($sentence =~ /under/)which would print out a message if we had either of the following $sentence = "Up and under";But it's often much easier if we assign the sentence to the special variable $_ which is of course a scalar. If we do this then we can avoid using the match and non-match operators and the above can be written simply as if (/under/)The $_ variable is the default for many Perl operations and tends to be used very heavily.
More on REsIn an RE there are plenty of special characters, and it is these that both give them their power and make them appear very complicated. It's best to build up your use of REs slowly; their creation can be something of an art form.Here are some special RE characters and their meaning . # Any single character except a newlineand here are some example matches. Remember that should be enclosed in /.../ slashes to be used. t.e # t followed by anthing followed by e There are even more options. Square brackets are used to match any one of the characters inside them. Inside square brackets a - indicates "between" and a ^ at the beginning means "not": [qjk] # Either q or j or kAt this point you can probably skip to the end and do at least most of the exercise. The rest is mostly just for reference. A vertical bar | represents an "or" and parentheses (...) can be used to group things together: jelly|cream # Either jelly or cream Here are some more special characters: \n # A newline Clearly characters like $, |, [, ), \, / and so on are peculiar cases in regular expressions. If you want to match for one of those then you have to preceed it by a backslash. So: \| # Vertical barand so on.
Some example REsAs was mentioned earlier, it's probably best to build up your use of regular expressions slowly. Here are a few examples. Remember that to use them for matching they should be put in /.../ slashes[01] # Either "0" or "1"
Get the output from a command and split the result open(OUTPUT, "snmpwalk -v1 -c ${communitystring} ${stack} IF-MIB::ifName.${port_id}|");@OUTPUT = <OUTPUT>; close(OUTPUT); $switch_port="@OUTPUT"; chomp $switch_port; $switch = ((split /Slot: /, ${switch_port})[1]); $switch = ((split / Port:/, ${switch})[0]);
|