我有一些文档,我希望在每行的开头和结尾添加一些内容。原始文档如下所示:
firstLine
secondline
我想把它变成这个:
put 'firstLine';
put 'secondline';
通过使用以下Perl脚本,我只能将其转换为:
put 'firstLine';
';put 'secondline';
似乎在第一行的末尾和第二行的开头有一个$
。有人可以帮我弄清楚下面的Perl脚本有什么问题吗?
use File::Find;
use strict;
my ($filename, @lines, $oldterm, $newterm); #,$File::Find::name);
my $dir = ".";
open MYFILE, ">error.txt" or die $!;
find(\&edits, $dir);
sub edits() {
$filename = $File::Find::name;
if (grep(/\.txt$/, $filename)) { #only process the perl files
# open the file and read data
# die with grace if it fails
open(FILE, "<$filename") or die "Can't open $filename: $!\n";
@lines = <FILE>;
close FILE;
# open same file for writing, reusing STDOUT
open(STDOUT, ">$filename") or die "Can't open $filename: $!\n";
# walk through lines, putting into $_, and substitute 2nd away
for (@lines) {
s/(&.+)/' "$1" '/ig;
s/^/put '/ig;
s/$/';/ig;
print;
}
#Finish up
close STDOUT;
}
}
答案 0 :(得分:8)
根本不使用正则表达式:你已经在@lines数组中分隔了这些行:
for ( @lines ) {
chomp; # remove newline at the end of the implicit variable $_
print "puts '$_'\n";
}
答案 1 :(得分:1)
如果你一步到位,你应该有更好的运气。类似的东西:
s/^(&.+)$/put '$1';/im;