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).


In reply to Re: Tie::File with absolute path of the file by haukex
in thread Tie::File with absolute path of the file by colox

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.