Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I want to run a perlscript to modify several similar files.
I've got it going one one file:

@ARGV="foo.bar";
$^I=".bk";
while (<>) {

etc...

What is the best way to do this on several files in the same directory?

Replies are listed 'Best First'.
Re: modifying multiple files
by Hofmator (Curate) on Aug 03, 2001 at 20:04 UTC

    To do it your way you would just write @ARGV = qw/file1 file2 file3/; but you can just provide these filenames from the command line, so if your perl script is called do_it then you call it with perl do_it file1 file2then $ARGV[0] in your program would contain file1 and $ARGV[1] would be file2.

    You can specify the backup copy also from the command line with perl -i.bk do_it foo.barinstead of using $^I = '.bk';

    -- Hofmator

      That's helpful, thanks -
      I have a lot of files, though; is there a way to automatically do it to all .bar files?

        yes, just use the filename expansion of your shell, i.e. perl -i.bk do_it *.bar and all files in the current directory ending in .bar are processed by the script in place (the backups have the additional ending .bk)

        -- Hofmator

Re: modifying multiple files
by physi (Friar) on Aug 03, 2001 at 20:21 UTC
    try it with readdir
    like that:
    opendir DIR, "dirname"; @files = readdir DIR; closedir DIR; for $file (@files) { do whatever you want ... }
    Remember to throw away files you don't need, or just use the files you are looking for. i.e.:
    for $file (@files) { next if $file =~ /^.+/; }
    or
    for $file (@files) { next if $file !~ /\.whatever/; do your stuff here }
    ----------------------------------- --the good, the bad and the physi-- -----------------------------------
Re: modifying multiple files
by JP Sama (Hermit) on Aug 03, 2001 at 20:00 UTC
    perhaps a glob, and a foreach would do the job...

    post more info, so i can help you a little more...

    #!/jpsama/bin/perl -w
    $tks = `mount`;
    $jpsama = $! if $!;
    print $jpsama;