regex - Perl:Chomping字符串后,它不打印字符串的值

标签 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 函数会破坏或隐藏数据,因此当我在 chomp $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();

最佳答案

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

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

修复您的输入文件

dos2unix file

或者删除 CR 和 LF。

s/\s+\z//   # Instead of chomp

关于regex - Perl:Chomping字符串后,它不打印字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640290/

相关文章:

正则表达式将字符串golang中的子字符串更改为大写

Javascript 将正则表达式与组匹配

ruby - 是否有时会在没有 'gets' 的情况下使用 'chomp' ?

arrays - 如何使用 chomp

javascript - Visual Studio 警告这个正则表达式的语法怎么样?

regex - Graylog 正则表达式搜索文本中的数字

perl - 为什么 Perl 的编码层没有任何作用?

perl - 为什么错误消息不同?

perl - 您如何处理 Perl Web 应用程序中的鼠标控制?