Perl:截断字符串后,它不会打印字符串的值 [英] Perl: After Chomping a string, it does not print the string's value

查看:95
本文介绍了Perl:截断字符串后,它不会打印字符串的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我目前正在尝试编写一个Perl脚本,该脚本可读取文件并写入另一个文件.目前,我遇到的问题是从已解析的行中删除换行符.我输入了这样的文件

So I am currently trying to write a perl script that reads to a file and writes to another. Currently, the problem that I have been having is removing new line characters from parsed rows.I feed in a file like this

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 …

最终,我试图将其设置为这样的格式

Ultimately I am trying to put it into a format like this

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函数以某种方式破坏或隐藏了数据,所以当我将$ row切掉后进行打印时,什么也没有显示.


it sucessfully removes recognizes to each number but then I want to remove the \n then replace the "." with a ",". Sadly the chomp function destroys or hides the data some how so when I print after chomping $row, nothing shows... What should I do to correct this?

#!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上,导致下一行输出覆盖最后一行输出.

Your lines end with CR LF. You remove the LF, leaving the CR behind. Your terminal is homing the cursor on CR causing the next line output to overwrite the last line output.

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

修复您的输入文件

dos2unix file

或删除CR和LF.

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

这篇关于Perl:截断字符串后,它不会打印字符串的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆