微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Learning Perl: 8.5. Interpolating into Patterns

@H_404_0@
@H_404_0@

Previous Page

Next Page

 

8.5. Interpolating into Patterns

The 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.

Previous Page

Next Page

@H_404_0@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐