
#Perl string compare code#
The confusion stems from the fact that Perl actually has two sets of comparison operators - one for comparing numeric values and one for comparing string American Standard Code for Information Interchange (ASCII) values. I think this format is a little easier to read, and as a final note, you'll see this syntax used more commonly in Perl programs than the first syntax I showed. Perl comparison operators can sometimes be confusing to new Perl programmers. There are multiple ways we can compare whether strings are equal or not. Using these variables is not recommended in scripts when performance. When you're performing a simple pattern match like this you can use this format, without the leading m character or the parentheses. (dollar backtick) holds the part of the string before (to the left of) the regex match. Return unless $string =~ /print|allow|okay/ Here's how you can simplify that line of code: Match Regular Expression - m// Substitute Regular Expression - s/// Transliterate Regular Expression - tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. There's actually a shorter way to write that return unless line of code, but I didn't want to throw it at you all at once. There are three regular expression operators within Perl. The only lines that are printed are those that match the three patterns I'm performing a comparison against: print, allow, and okay. Return unless ($string =~ m/(print|allow|okay)/) Īs you can see I call the print_filter method four times, passing in different strings. These patterns can be anywhere in the string that is passed in, but they must be in lower case. In this case I only print the strings that contain the patterns print, allow, or okay. a period in a regular expression tells Perl to match any single character in its place. In this sample program I have a method named print_filter that prints lines that only match specific, simple patterns. The match operation returns true if the pattern is found in the string. The Perl source code below shows a simple example of the pattern matching that I'm doing in my Perl script. The cmp operator is used for comparing two strings and finding out if the first is less than or equal to, or greater than the second string.


This is pretty easy in this case, in part because it's easy to match a string against multiple patterns in Perl, and also because my patterns are very simple - no regular expressions involved. For a Perl program that I'm working on right now, I need to match the elements of an array of strings against several patterns, and then take an action if the current string matches one of my patterns.
