O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix I. Answers to Chapter 9 Exercises

Answer 9.1: The first one is easy. You use an alternate delimiter for your match operator. Since you’re not using the default // delimiters, you need the leading m. I like to use the pipe (“|”) character, but you can use other characters, or even the paired characters like { and }. These are the same thing:

m|/usr/bin/perl|
m(/usr/bin/perl)
m{/usr/bin/perl}
m,/usr/bin/perl,

To match a web address with a fragment identifier, you can cheat a little. Rather than get into the edge and special cases, look for the beginning http:// then non-whitespace characters (\S) followed by the # character which starts the fragment name (assuming any literal #’s are properly escaped). Using the paired curly braces as your delimiter, your pattern looks like:

m{http://(\S+)#}

Matching a real C++ comment is rather tricky. In the simple case, it’s just the // until the end of the line. What if that // shows up in a literal string instead of a comment, though? Well, then, this won’t work. I just want you to use an alternate delimiter, so here’s the simple regular expression. If you really wanted to do this, you’d have to completely parse the C++ code, and luckily for you, Learning Perl didn’t cover that:

m[//]

However, if you are curious, perlfaq6 has a complicated regular expression that tries to do this for any situation.

Answer 9.2: The regular expression from Exercise 8.1 wanted to match a string with an “a”, “b”, or “x” of either case:

m/[abxABX]/;

Now you know that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required