eli1128
eli1128

Reputation: 134

perl print only the last line of the array

I am trying to print the array but the out put contain only the last line of the array. the partial code is as follow.

open OUT, "> /myFile.txt"
    or die "Couldn't open output file: $!";

foreach (@result) {

    print OUT;
}

the out put is

List Z

which is the last line, but when I do print "@result" the out put is

List A

List B

List C  so on...

I am little bit confuse why the results are different on the same array.

Upvotes: 2

Views: 1435

Answers (3)

protist
protist

Reputation: 1220

the problem is here

open OUT, "> /myFile.txt"

this should be

open OUT, ">>", "/myfile.txt"

What you wrote overwrites the entire file for each iteration of the foreach(@result) loop. What you are intending to do is append to it (">>"). ">>" appends, ">" overwrites.

Also take note of how i broke ">> /myfile.txt" into ">>", "/myfile.txt". This is both more secure, and more robust for less specific applications of open.

Upvotes: 2

Borodin
Borodin

Reputation: 126762

Foreign line terminators from any platform can easily be fixed by clearing whitespace from the end of the line and adding it back when printing it

Like this

open my $out, '>', '/myFile.txt' or die "Couldn't open output file: $!";

foreach (@result) {
  s/\s+$//;
  print $out "$_\n";
}

or

foreach my $line (@result) {
  $line =~ s/\s+$//;
  print $out "$line\n";
}

Upvotes: 0

TLP
TLP

Reputation: 67920

Working on a hunch, I tried adding \r to the end of your input lines, and sure enough, it creates the illusion that only the last line of your input is printed to the file. Here's the code to test it:

use strict;
use warnings;

my @result = map "$_\r", 'A' .. 'Z';

open (OUT, "> myFile.txt") or die("Couldn't open output file: $!");
foreach (@result) {
    print OUT ;
}

What you have probably done is performed chomp on lines from a file from a different operating system (DOS, Windows), which does not strip the \r line endings. Hence, when the lines are printed, the lines overwrite each other.

If this is what is wrong, the solution is to use the dos2unix tool to fix your files, or to use:

s/\s+\z//; 

to strip your newlines.

You may inspect your input by using the Data::Dumper module, using the option Useqq, e.g.:

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper \@result;

If these whitespace characters are in your output, they will then be visible.

Upvotes: 7

Related Questions