Tree
Tree

Reputation: 10342

File is adding one extra space in each line

I am trying to add all the elements in array using push . then i stored into another file

but begining of file i am seeing one whitespeace in every thing ..

What is the issue .. any one before face this issue .

open FILE , "a.txt"

while (<FILE>)
{

  my $temp =$_;

  push @array ,$temp;

}
close(FILE);

open FILE2, "b.txt";
print FILE2 "@array";
close FILE2;

Upvotes: 2

Views: 2412

Answers (3)

cjm
cjm

Reputation: 62089

You put quotes around "@array". That makes it a string interpolation, which for arrays is equivalent to join($", @array). The default value for $" is (guess what?) a space.

Try

print FILE2 @array;

Upvotes: 4

daxim
daxim

Reputation: 39158

When you quote an array variable like this: "@array" it gets interpolated with spaces. That's where they come from in your output. So do not quote if you do not need or want this sort of interpolation.

Now let's rewrite your program to modern Perl.

use strict;
use warnings FATAL => 'all';
use autodie qw(:all);

my @array;
{
    open my $in, '<', 'a.txt';
    @array = <$in>;
}

{
    open my $out, '>', 'b.txt';
    print {$out} @array;
}

Upvotes: 7

mob
mob

Reputation: 118605

open usually takes another argument that specifies whether the file is opened for input or for output (or for both or for some other special case). You have omitted this argument, and so by default FILE2 is an input filehandle.

You wanted to say

open FILE2, '>', "b.txt"

If you put the line

use warnings;

at the beginning of every Perl script, the interpreter will catch many issues like this for you.

Upvotes: 2

Related Questions