LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PERL:How to print the lines of a opening file without '\n' in the end? (https://www.linuxquestions.org/questions/programming-9/perl-how-to-print-the-lines-of-a-opening-file-without-%5Cn-in-the-end-914811/)

jimtony 11-21-2011 07:44 PM

PERL:How to print the lines of a opening file without '\n' in the end?
 
Hi all,

I found that while reading a line from a file,perl will add a '\n' in the end when printing this line.
For example:
#!/usr/bin/perl

use strict;
use warnings;
open FILE,"anaconda.cfg" or warn $!;
while(<FILE>){
print "$_.....................";
}


the output is as follows:
# Kickstart file automatically generated by anaconda.
.....................%packages
.....................@admin-tools
.....................@base
.....................@core
.....................

But I don't want this output,I want the ".............."in the end of each lines,as follows:
# Kickstart file automatically generated by anaconda......................%packages.....................@admin-tools.....................@base.....................@core.....................

I think the perl will add '\n' in each line from the file,so how to delete the '\n' character?

jimtony 11-21-2011 08:19 PM

I solved this problem,use chomp function to delete the '\n'.
So the codes should be:
#!/usr/bin/perl

use strict;
use warnings;
my $line="sdfsdf";
open FILE,"anaconda.cfg" or warn $!;
while(($line=<FILE>)){
chomp($line);
print "$line.....................";
}

The output is:
# Kickstart file automatically generated by anaconda......................%packages.....................@admin-tools.....................@base.....................@core.....................

neonsignal 11-21-2011 08:22 PM

Perl doesn't add a newline, the newline comes from the file. Use chomp to strip it.
Code:

#!/usr/bin/perl

 use strict;
 use warnings;
 open FILE,"anaconda.cfg" or warn $!;
 while(<FILE>){
  chomp;
  print "$_.....................";
 }



All times are GMT -5. The time now is 03:12 AM.