Learning Perl: 8.5. Interpolating into Patterns
2010-07-21 17:56
246 查看
8.5. Interpolating into PatternsThe regular expression is double-quote interpolated as if it were a double-quoted string. This allows us to write a quick grep-like program like this:#!/usr/bin/perl -w my $what = "larry"; while (<>) { if (/^($what)/) { # pattern is anchored at beginning of string print "We saw $what in beginning of $_"; } } The pattern will be built up out of whatever's in $what when we run the pattern match. In this case, it's the same as if we had written /^(larry)/, looking for larry at the start of each line. We didn't have to get the value of $what from a literal string and could have gotten it from the command-line arguments in @ARGV: my $what = shift @ARGV; If the first command-line argument is fred|barney, the pattern becomes /^(fred|barney)/, looking for fred or barney at the start of each line.[ ] The parentheses (which weren't necessary when searching for larry) have become important because without them we'd be matching fred at the start or barney anywhere in the string. [ ] The astute reader will know that you can't generally type fred|barney as an argument at the command line because the vertical bar is a shell metacharacter. See the documentation to your shell to learn about how to quote command-line arguments. With that line changed to get the pattern from @ARGV, this program resembles the Unix grep command. But we have to watch out for metacharacters in the string. If $what contains 'fred(barney', the pattern will look like /^(fred(barney)/. You know that can't workit'll crash your program with an invalid regular expression error. With some advanced techniques,[*] you can trap this kind of error (or prevent the magic of the metacharacters in the first place) so it won't crash your program. But for now, just know that if you give your users the power of regular expressions, they'll need the responsibility to use them correctly. [*] In this case, you would use an eval block to trap the error, or you would quote the interpolated text using quotemeta (or its /Q equivalent form) so it's no longer treated as a regular expression. |
相关文章推荐
- Learning Perl: 7.2. Using Simple Patterns
- Perl: 3.5. Interpolating Arrays into Strings
- learning perl(一)标量 数组 哈希
- Learning Perl: 1.4. How Do I Make a Perl Program?
- Perl Learning: 2.9. The while Control Structure
- Learning Perl: 4.8. The use strict Pragma
- Learning Perl: 7.1. What Are Regular Expressions?
- Perl学习笔记 Learning Perl Chapter II
- Perl学习笔记 Learning Perl Chapter IV
- Learning Perl: 1.5. A Whirlwind Tour of Perl
- Learning Perl: 3.4. List Assignment
- Learning Perl: 4.9. The return Operator
- Learning Perl(Perl语言入门)学习笔记(3)
- 《Learning Javascript Design Patterns》小结
- perl embeded into c++ 完全攻略
- Perl Learning 3 Subroutine
- Delve into Manage memory Essentials learning(3)
- Perl Learning - 8 (I/O, <>, print(), @ARGV)
- Perl Learning - 10 (hash)
- Perl Learning - 12 (Perl RE)