in reply to Changing data in alot of files

Hi there!

You definitely want Jason-Mark Dominus's Tie::File CPAN module (part of the CORE since Perl 5.8.0)

An example:

use Tie::File for my $file (@files) { my @file; tie @file, 'Tie::File', $file or die $!; for my $line ( @file ) { # do stuff on the lines you want # it reflects 'inmediately' on the file } untie @file; }

Definitely million times better!

best regards,

Update:
While "perl -wnli.bak -e 's///;s///...' *" will make a backup copy of the files processed so far (if it happens to crash), it will scan the whole file, no matter what. From your example that seems what you need, so it's a very good reply (I am voting for it) but I forgot to add that if you know which lines you are changing (headers, or if they come from a template) with Tie::File you can access individual lines using $file5 (the 6th line). What's more, you can easily cut the loop ig you know all changes will be in the first 50 lines of header, or whatever. Tie::File only reads as many lines as needed to get the job done, and it's very fast (not new files, works inside the file itself) and AFAIK completely reliable. You can get it from CPAN (www.cpan.org) (perl -MCPAN -e 'install Tie::File' if you have it configured to go beyond a proxy; try doing perl -MCPAN -e shell first, and write the 'install Tie::File' there) for Perl 5.6.1 (I have it in production code with this release of Perl on GNU/Linux) or if you're using ActivePerl, try using the tool to install compiled modules in Perl (was it called ppm?). Good luck,

--
our $Perl6 is Fantastic;

Replies are listed 'Best First'.
Re: Re: Changing data in alot of files
by Anonymous Monk on Jul 10, 2003 at 17:13 UTC
    My NT server is using Perl 5.6.1 so I dont think I can use your example? Is my example the most efficient way of doing what I need to do??

      Most efficient? Not a chance. Doing linear scans of the data like that isn't going to win you any points in the efficiency department. However, it is vastly easier to code then trying to do in-place editing of the file (assuming you need to do this as part of a larger program, so that dragonchild's response wouldn't help you much).

      If the data is small, you could slurp the file into a single scalar and then run your s///g's. You may or may not see any performance benifit doing it this way, depending on your hard drive cache, IO buffering, OS implementation, phase of the moon, etc.

      Still, Tie::File probably satisifies both efficency and ease of development. I've never used the module myself, but I don't know of any reason why it shouldn't work on NT.

      ----
      I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
      -- Schemer

      Note: All code is untested, unless otherwise stated