【发布时间】:2015-09-15 09:36:18
【问题描述】:
我目前需要一个正则表达式来搜索和替换所有 |–|与 |-|。我正在更换|`|与 |'|它正在使用:
while($_ =~ s/`/'/g)
{
print "Line: '$.'. ";
print "Found '$&'. ";
}
但是,使用相同的正则表达式不适用于我的以下所有尝试:
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\&ndash/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
while($_ =~ s/&ndash/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
目前的脚本如下:
#!/usr/bin/perl
use strict;
use warnings;
my $FILE;
my $filename = 'NoDodge.c';
open($FILE,"<service.c") or die "File not opened";
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
while (<$FILE>)
{
while($_ =~ s/`/'/g)
{
print "Line: '$.'. ";
print "Found '$&'. ";
}
while($_ =~ s/\–/-/g)
{
print "Line: '$.'. ";
print "Found '$&'.\n";
}
print $fh $_;
}
close $fh;
print "\nCompleted\n";
当前结果示例:
行:'152'。找到'`'。
行:'162'。找到'`'。
完成
解决方案: 由鲍罗丁提供,
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use open qw/ :std :encoding(utf8) /;
my $FILE;
my $fh;
my $readfile = 'service.c';
my $writefile = 'NoDodge.c';
open($FILE,'<',$readfile) or die qq{Unable to open "$readfile" for input: $!};
open($fh, '>',$writefile) or die qq{Unable to open "$writefile" for output: $!};
while (<$FILE>)
{
while(s/–/-/g)
{
print "Found: $& on Line: $.\n";
}
while(s/`/'/g)
{
print "Found: $& on Line: $.\n";
}
print $fh $_;
}
close $fh;
close $FILE;
print "\nService Migrated to $writefile\n";
示例输出:
找到:- 在线:713
发现:`在线:713
找到:-在线:724
发现:`在线:724
发现:`在线:794
服务迁移到 NoDodge.c
【问题讨论】:
-
不需要
$i来计算行号。您可以使用$.,它保存当前文件句柄行号。见 perlvar。 -
谢谢simbabque,我去看看