Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem reading a file

Status
Not open for further replies.

user2base

Technical User
Oct 16, 2002
29
0
0
GB
I've quoted below a basic script that reads a file and prints its content. Whatever the file is (/etc/hosts is just an example), the script adds a space for all the lines following line #1, i.e:

line 1
line 2
line 3

I would like it to return the file as it is, i.e:
line 1
line 2
line 3

What's wrong !?


#! /usr/bin/perl -w
use strict;

sub read_file{
my $file = shift;
my @file;

open (FILE, &quot;< $file&quot;) or die &quot;Can't open $file: $! \n&quot;;
@file = <FILE>;
close (FILE) or die &quot;FH didn't close: $!&quot;;
return @file;
}


my @output = read_file(&quot;/etc/hosts&quot;);

print &quot;@output\n&quot;;
 
When you print out an array directly from a string like
Code:
print &quot;@output\n&quot;;
Perl, by default, space separates the elements and prints them. Since you haven't chomp()ed off the newlines from each line, your array, as a string, would look like
Code:
&quot;line 1\n line 2\n line 3\n&quot;
        ^^^      ^^^   added space separation
Instead print out the array as
Code:
print $_ for @output;
# or just
print for @output;
jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top