Except it's just as easy to load the file into memory and write it back out when it's that small.
By "ease of implementation" I meant:
open my $ifh, '<', $file or die $!; chomp( my @a = <$ifh> ); close $ifh; # vs. use Tie::File; tie my @a, 'Tie::File', $file; # and open my $ofh, '>', $file or die $!; print $ofh $_,"\n" for @a; close $ofh; # vs. untie @a;
I think several arguments, some subjective, could be made in either direction which one "easier". Whether it's worth the cost (speed and memory penalty) depends on the application, and of course the user must be aware of the penalty in the first place, so it's definitely good to caution. I just personally wouldn't reject the module outright.
Granted, if it's about reducing the length of the code, it's also possible to do something like this, although it still has a speed penalty, just not quite as bad as Tie::File:
use Path::Class qw/file/; my @a = file($file)->slurp(chomp=>1); ... file($file)->spew_lines(\@a);
A while(<>) should still be faster than any of the above. (I ran some quick back-of-the-envelope benchmarks with /usr/share/dict/words.)
Karl asked about "serious" use cases. Under the conditions I named, I'd say it's just a matter of TIMTOWTDI, but if you were to say that's not a "serious" use case, then you wouldn't be wrong. I think I'll be cautioning against Tie::File more in the future.
|Replies are listed 'Best First'.|
Re^8: Loading a part of the file to array using Tie::File
by ikegami (Patriarch) on Nov 26, 2017 at 07:51 UTC
by haukex (Bishop) on Nov 26, 2017 at 09:04 UTC