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

I have a lots of .txt files containing numerical data.
The following code opens a program called platon and it in turn opens a single .txt file and does various things with it.
($in_filename, $out_filename) = @ARGV; $out_filename = $in_filename if ( !($out_filename) ); $ins_filename = "$in_filename.txt"; system ("platon -c $txt_filename");

How would I change this code so it opens all my .txt files one after another (they are numbered sequentially).
cheers harry

Replies are listed 'Best First'.
Re: opening files
by Aristotle (Chancellor) on Jul 08, 2002 at 13:50 UTC
    Why do you append the .txt extension to $ins_filename but use $txt_filename in your system? Anyway:
    ($in_filename, $out_filename) = @ARGV; $out_filename = $in_filename if ( !($out_filename) ); for my $num (1..20) { system ("platon", "-c", "$in_filename$num.txt") +}
    Note it's much better to use the multi-argument form of system. See perldoc -f system.

    Makeshifts last the longest.

Re: opening files
by jjohn (Beadle) on Jul 08, 2002 at 15:03 UTC

    How would I change this code so it opens all my .txt files one after another (they are numbered sequentially).

    In a Bourne-like command shell (like bash), you could do:

    for i in *txt; do platon -c $i; done

    In Perl on a Unix box (or a shell that expands the command line arguments for you), this should work:

    for my $infile (@ARGV){ next unless -e $infile; system("platon -c $infile"); }

    This program expects to be passed the whole list of files to process, like this (assuming this code above is in a file called 'batch.pl'):

    $ perl batch.pl *.txt

    The -e file test operator attempts to make sure that the argument to be processed is an existing file. This is a small attempt to prevent a rogue user from abusing your script. In your environment security may not be an issue, but this sanity check is easy to do.

    I don't understand how the $out_filename argument is used in your code, so I've silently ignored it (well, not so silently, I guess :-)

    If I were on a Unix system, I'd opt for the small bit of shell script magic to drive your platon program. Of course, I may not be understanding some of your requirements (i.e. do the source files need to be executed in a particular order? Must existing outfiles not be overwritten?, etc). Of course, Perl is great for bring a Unix-like environment to a non-Unix OS. I've done a bit of Perl scripting on NT boxes and Perl has really saved me a lot of MSDOS batch language pain.

    Hope this helps.