【问题标题】:Perl: After Chomping a string, it does not print the string's valuePerl:Chomping一个字符串后,它不会打印字符串的值
【发布时间】:2015-04-15 01:55:13
【问题描述】:

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

【问题讨论】:

  • open my $in, '&lt;:crlf', "file.txt";

标签: regex perl chomp


【解决方案1】:

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

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

修复你的输入文件

dos2unix file

或将 CR 与 LF 一起移除。

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

【讨论】:

  • 我猜你的意思是s/\R\z//
  • @tchrist,如果你必须处理尾随空格很重要的格式,我很同情你,你会使用s/\R\z//。对于我们其他人来说,s/\s+\z// 更好。
  • @Joshua,这无济于事。他没有LF LF;他有 CR LF。
猜你喜欢
  • 2021-02-24
  • 2017-06-25
  • 2012-09-11
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 2020-01-03
  • 2021-04-03
  • 1970-01-01
相关资源
最近更新 更多