Pergunta

I have perl code (called aggregator.pl) that reads some data from a file called 'testdata.csv' through the command

open (F,'testdata.csv');  
my @lines=<F>;    
close(F);

opens a new file handle for the output

open (F1,'>>testdata_aggregates.csv');

and appends to this output file 'testdata_aggregates.csv' the results of some calculations.

To launch my perl code I simply type in my command prompt:

$ perl aggregator.pl

Now, I have different data files, called e.g 20100909.csv or 20100910.csv and I would like to change my perl code so that when I launch my code from the command prompt I tell perl the name of the input file he should use (say, '20100909.csv') and that he should name the output file accordingly (say '20100909_aggregates.csv', basically, adding _aggregates to the input filename).

Any advice on how to change my code and how would I have to launch the new code adding the name of the data_input file he should use?

Foi útil?

Solução

Just accept parameters via @ARGV.

Your script should open with:

use strict;
use warnings;
use autodie;

die "Usage: $0 Input_File Output_File\n" if @ARGV != 2;

my ($infile, $outfile) = @ARGV;

And later in your file

open (F, '<', $infile);

# ...

open (F1,'>>', $outfile);

Outras dicas

One would usually rewrite such an application that it reads from STDIN and simply writes to STDOUT. When the program is then invoked on the command line, redirection operators can be used to specify the files:

$ perl aggregator.pl <testdata.csv > testdata_aggregates.csv
$ perl aggregator.pl <20100909.csv > 20100909_aggregates.csv
...

What changes inside the script? We don't open a file F, instead: my @lines = <>. We don't print to F1, instead we print to STDOUT, which is selected implicitly: print F1 "foo\n" becomes print "foo\n".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top