【问题标题】:Why is this substitution involving the end of each line adding more to the beginning of the line?为什么这种涉及每行末尾的替换会在行首添加更多内容?
【发布时间】:2011-02-01 04:07:12
【问题描述】:

我有一些文档,我想在每行的开头和结尾添加一些内容。原始文档如下所示:

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;
    }
}

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    根本不要使用正则表达式:您已经在@lines 数组中分隔了行:

    for ( @lines ) {
        chomp; # remove newline at the end of the implicit variable $_
        print "puts '$_'\n";
    }
    

    【讨论】:

      【解决方案2】:

      如果你一步一步做到了,你应该会有更好的运气。比如:

      s/^(&.+)$/put '$1';/im;
      

      【讨论】:

        猜你喜欢
        • 2017-04-28
        • 1970-01-01
        • 2011-03-05
        • 2015-02-16
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多