Simply  Seth
Simply Seth

Reputation: 3496

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";
}

Upvotes: 1

Views: 4540

Answers (4)

gjc
gjc

Reputation: 1

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";

Upvotes: 0

Simply  Seth
Simply Seth

Reputation: 3496

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)

Upvotes: 0

OMG_peanuts
OMG_peanuts

Reputation: 1817

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)

Upvotes: 1

Anon.
Anon.

Reputation: 59983

while(<>) {chomp;print;print '\n';}

Upvotes: 3

Related Questions