http://qs321.pair.com?node_id=1204924


in reply to Tie::File with absolute path of the file

In a recent thread I was sufficiently convinced by other monks that Tie::File - even though I still think it's kind of "neat" - is not a good choice in a serious application. On a large file it's much too inefficient, and even on a small file it's still more efficient to just read the entire file into an array and write it back out after modifying. So either:

open my $ifh, '<', $filename or die "$filename: $!"; chomp( my @array = <$ifh> ); close $ifh; # modify @array here open my $ofh, '>', $filename or die "$filename: $!"; print $ofh $_,"\n" for @array; close $ofh;

Or, to demonstrate a while(<>) loop and plug one of my own modules ;-) see File::Replace:

use File::Replace; my $repl = File::Replace->new($filename); my $infh = $repl->in_fh; while (my $line = <$infh>) { chomp($line); # modify $line here print {$repl->out_fh} $line, "\n"; } $repl->finish;

As for the problem you're having with Tie::File, I think both tangent and toolic have a very good point about write permissions. I would also add that perhaps using proper modules to handle file names platform independently might help with mitigating headaches about slashes etc. in filenames: either the core File::Spec, or, with a much nicer interface, Path::Class (there's also Path::Tiny with a similar interface, but be aware that that's restricted to Windows an *NIX).