在Perl中覆盖区分大小写的正则表达式

是否有可能覆盖Perl中先前定义的正则表达式的区分大小写?例如,如果我有以下内容
my $upper = qr/BLAH/x;
my $lower = qr/$upper/xi;
warn "blah" =~ $lower

我希望第三行打印出一个积极的匹配.

解决方法

您可以将/ i添加到regexp,如下所示:
use re qw( is_regexp regexp_pattern );

sub make_re_case_insensitive {
   my ($re) = @_;

   return "(?i:$re)" if !is_regexp($re);

   my ($pat,$mods) = regexp_pattern($re);
   if ($mods !~ /i/) {
      $re = eval('qr/$pat/'.$mods.'i')
         or die($@);
   }

   return $re;
}

但这不会影响qr /(? – i:BLAH)/.

This is more of a code reuse question,so I don’t have to make two very similar regex that test either uppercase or lowercase.

my $pat = 'BLAH';
my $re1 = qr/$pat/x;
my $re2 = qr/$pat/xi;

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...