1

在下面的代码中,我想制作gf打印相同的输出。差异($RE{num}{real})$以字符串形式给出。有人现在如何将其转换为正则表达式?

~/linux/test/perl/library/Regexp/Common/%RE/num/real$ cat main1.pl
#!/usr/bin/env perl

use strict;
use warnings;
use autodie;

use FindBin;
use lib "$FindBin::Bin/.";

use Regexp::Common;

sub f {
  my $x = shift;
  $x =~ s/^($RE{num}{real})$/$1 is real/;
  print "$x\n";
}

f("1.5");
f("15f");
f("1e5");
f(".1e5");
f("a");

my $regex_str='($RE{num}{real})';
#Neither of the following work.
#$regex_str=eval $regex_str;
#$regex_str=qr{$regex_str};
sub g {
  my $x = shift;
  $x =~ s/^$regex_str$/$1 is real/;
  print "$x\n";
}

g("1.5");
g("15f");
g("1e5");
g(".1e5");
g("a");


~/linux/test/perl/library/Regexp/Common/%RE/num/real$ ./main1.pl 
1.5 is real
15f
1e5 is real
.1e5 is real
a
1.5
15f
1e5
.1e5
a
4

3 回答 3

2
my $regex_str="($RE{num}{real})";

或者

my $regex_str=qr/($RE{num}{real})/;
于 2013-04-07T22:08:22.517 回答
1

Single quotes in Perl do not interpolate variables. Use double quotes to interpolate a variable. To create a regular expression, though, you may use the qr// operator:

my $regex = qr/$RE{num}{real}$/;
if ( $x !~ $regex ) { 
于 2013-04-07T20:18:39.903 回答
0

一个问题是你$最后有两个令牌:

my $regex_str='$RE{num}{real}$';
...
if( $x !~ /^$regex_str$/) {
于 2013-04-07T20:19:58.567 回答