Reputation: 1091
This is in continuation with this ->Read and Write to a file in perl question.
The following code worked perfectly fine for reading and writing to the same file:
use Tie::File;
use strict;
use warnings;
my $filename = "out.txt";
my @array;
tie @array, 'Tie::File', $filename
or die "can't tie file \"$filename\": $!";
for my $line (@array) {
$line = "<$line>";
}
untie @array;
But when I did the following the changes were not reflected in the file :
use Tie::File;
use strict;
use warnings;
my $filename = "out.txt";
my @array;
tie @array, 'Tie::File', $filename
or die "can't tie file \"$filename\": $!";
my $len = @array;
for ($i = 0; $i < $len ; $i++) {
$line = $array[$i];
$line = "<$line>";
}
untie @array;
Can someone help me with this problem ? Yes I know I can use the for loop above, knowing this may help me solve some other problems too. Thank you.
Upvotes: 0
Views: 1467
Reputation: 385506
In the first snippet, you're modifying the elements of @array
(via the alias $line
).
In the second, you're not modifying any elements of @array
. Change
$line = $array[$i];
$line = "<$line>";
to
$line = $array[$i];
$line = "<$line>";
$array[$i] = $line;
or simply
$array[$i] = "<$array[$i]>";
Note that using Tie::File is an awful way to do what you are doing.
Upvotes: 4