Perl: After Chomping a string, it does not print the string's value

爷,独闯天下 提交于 2019-12-31 03:38:04

问题


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…

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();

回答1:


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

Fix your input file

dos2unix file

or remove the CR along with the LF.

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


来源:https://stackoverflow.com/questions/29640290/perl-after-chomping-a-string-it-does-not-print-the-strings-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!