Perl:在对字符串进行Chomping之后,它不会打印字符串的值

时间:2015-04-15 01:55:14

标签: regex perl chomp

所以我目前正在尝试编写一个读取文件并写入另一个文件的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();

1 个答案:

答案 0 :(得分: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