简体   繁体   中英

perl: how do I read all lines from a file and print as one line of text

I am trying to return the output of a file replacing newlines with \\n without using CPAN

Here is what I have so far

#! /usr/local/bin/perl 

if ( $#ARGV = "1" )     {
    print "$ARGV[0]\n";

    my $file = "$ARGV[0]";
    my $document = do {
        local $/;
        open my $fh, "<", $file
          or die "could not open $file: $!";
        <$fh>;
    };
    print "Doc: $document\n";
}
while(<>) {chomp;print;print '\n';}

You could use the slurp mode (no more need for a while loop) and some regexp :

print map { $_ =~ s/\n/\\n/; $_ } (<>); 

Or some special variables :

my @a = <>;
$\ = $, = '\n';
chomp @a;
print @a;

($\\ is the output record separator, and $, is the output field separator. Both apply to the print operator)

I tried this ...

#! /usr/bin/perl 

if ( $#ARGV = "1" )     {
open FILE, "<", "$ARGV[0]" or die $!;
chomp $_;
@chars = map ({ $_ =~ s/\n/\\n/; $_ } (<FILE>)); 
print @chars;
print "@chars\n";
}

.. and it gives me the right output (except for some spaces that I need to learn how to strip out)

This is a long solution for clarity. In a nutshell, chomp will drop all trailing whitespace and control characters.

#!/usr/bin/perl

use strict;
use warnings;

my $filename = shift;
my @contents;
my $lines = 0;

if (! -e $filename) {
    print "Please provide a valid filename\n";
    exit;
}

print "Examining $filename\n";

open(FILE, "<$filename");

while (<FILE>) {
    chomp();
    push(@contents, $_);
    print ".";  
    $lines++;
    if ($lines % 10 == 0) {
        print "\n";
    }
}
close(FILE);

print "done\n";

foreach (@contents) {
    print "$_";
}

print "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM