Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl print only the last line of the array

Tags:

perl

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.

like image 653
eli1128 Avatar asked Jan 31 '26 07:01

eli1128


1 Answers

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.

like image 127
TLP Avatar answered Feb 02 '26 00:02

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!