tags:

views:

92

answers:

4

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";
}
+3  A: 
while(<>) {chomp;print;print '\n';}
Anon.
`print '\n'` will not do what you expect. (Try it and see.)
Ether
@Ether: It does exactly what I expect. The intent is to print a backslash followed by an "n", *not* a newline.
Anon.
Hmm ok, I completely misinterpreted what the OP wanted then. :) To be less ambiguous, you could say `'\\n'` instead.
Ether
+1  A: 

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)

OMG_peanuts
A: 

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)

Simply Seth
And what appens when you run your script without any arguments ?
M42
A: 

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