WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Basic · question 13 of 100

How do you perform pattern matching and substitution with regular expressions in Perl?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

In Perl, pattern matching and substitution with regular expressions is performed using the ‘= ‘ operator and the ‘s///‘ operator respectively.

1. Pattern Matching:

The ‘= ‘ operator is used to match a regular expression pattern against a string. The string is placed on the left side of the operator and the regular expression pattern is placed on the right side.

For example, let’s assume we have a string:

my $string = "The quick brown fox jumps over the lazy dog.";

If we want to check whether the string contains the word "fox" or not, we can use the ‘= ‘ operator as follows:

if ($string =~ /fox/) {
    print "Match found!";
}
else {
    print "Match not found.";
}

In the above code, we have used the regular expression ‘/fox/‘ to match the string. If the string contains the word "fox", the ‘if‘ block will be executed and "Match found!" will be printed on the screen; otherwise, the ‘else‘ block will be executed and "Match not found." will be printed.

2. Substitution:

The ‘s///‘ operator is used to substitute a regular expression pattern with a replacement string. The syntax for ‘s///‘ operator is as follows:

$string =~ s/regex/replacement/g;

In the above code, ‘regex‘ represents the regular expression pattern that you want to replace and ‘replacement‘ represents the string that you want to replace it with. The ‘g‘ modifier at the end stands for "global" and it means that all occurrences of the regular expression pattern in the string should be replaced.

For example, let’s assume we have the same string as above and we want to replace the word "fox" with "cat". We can use the ‘s///‘ operator as follows:

$string =~ s/fox/cat/g;

In the above code, the regular expression pattern ‘/fox/‘ is replaced with the replacement string "cat". The ‘g‘ modifier at the end ensures that all occurrences of the pattern in the string will be replaced.

After executing the above code, the new value of ‘$string‘ will be:

"The quick brown cat jumps over the lazy dog."

In conclusion, pattern matching and substitution with regular expressions in Perl can be performed using the ‘= ‘ and ‘s///‘ operators respectively. By using these operators, we can search for and manipulate text in a flexible and efficient way.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics