2

所以我目前正在尝试编写一个读取文件并写入另一个文件的 perl 脚本。目前,我遇到的问题是从解析的行中删除换行符。我输入这样的文件

BetteDavisFilms.txt
1.
Wicked Stepmother (1989) as Miranda
A couple comes home from vacation to find that their grandfather has …
2.
Directed By William Wyler (1988) as Herself
During the Golden Age of Hollywood, William Wyler was one of the …
3.
Whales of August, The (1987) as Libby Strong
Drama revolving around five unusual elderly characters, two of whom …

最终我试图把它变成这样的格式

1,Wicked Stepmother ,1989, as Miranda,A couple comes home from vacation to …
2,Directed By William Wyler ,1988, as Herself,During the Golden Age of …
3,"Whales of August, The ",1987, as Libby Strong,Drama revolving around five…

它成功删除了对每个数字的识别,但是我想删除 \n 然后替换“。” 带“,”。可悲的是,chomp 函数会破坏或隐藏数据,所以当我在 chomping $row 后打印时,什么都没有显示......我应该怎么做才能纠正这个问题?

#!bin/usr/perl
use strict;
use warnings;

my $file = "BetteDavisFilms";
my @stack = ();

open (my $in , '<', "$file.txt" ) or die "Could not open to read \n ";
open (my $out , '>', "out.txt" ) or die "Could not out to  file  \n";

my @array = <$in>;

sub readandparse() {
    for(my $i = 0 ; $i < scalar(@array); $i++) {
        my $row = $array[$i];

        if($row =~ m/\d[.]/) {
            parseFirstRow($row);
        }
    }
}

sub parseFirstRow() {
    my $rowOne = shift;
    print $rowOne; ####prints a number
    chomp($rowOne);
    print $rowOne; ###prints nothing
    #$rowOne =~ s/./,/;
}

#call to run program
readandparse();
4

1 回答 1

3

您的行以 CR LF 结尾。您移除 LF,留下 CR。您的终端将光标归位在 CR 上,导致下一行输出覆盖最后一行输出。

$ perl -e'
   print "XXXXXX\r";
   print "xxx\n";
'
xxxXXX

修复您的输入文件

dos2unix file

或将 CR 与 LF 一起移除。

s/\s+\z//   # Instead of chomp
于 2015-04-15T02:24:49.070 回答