开发者

How can I pass arguments to an external process from Perl?

开发者 https://www.devze.com 2022-12-20 16:43 出处:网络
I have a application executable, which runs with different parameters to produce different outputs. I want to give some parameters to this from the command line parameters of the script and others wil

I have a application executable, which runs with different parameters to produce different outputs. I want to give some parameters to this from the command line parameters of the script and others will be local to the script. Usage:

./dump-output.pl <version> <folder-name> <output-file>开发者_开发问答


my $version = $ARGV[0];
my $foldername = $ARGV[1];
my $outputfile = $ARGV[2];
my $mkdir_cmd = "mkdir -p ~/$foldername";

# There are 6 types of outputs, which can be created:
# 'a', 'b', 'c', 'd', 'e' or 'f'
my @outputtype = ('a', 'b', 'c', 'd', 'e', 'f');

my $mkdir_out = `$mkdir_cmd`;

for( $itr=0; itr<=5; itr++ ) {
    $my_cmd = "./my_app -v $version -t $outputtype[itr] -f $outputfile > ~/$foldername/$outputtype.out"
    $my_out = `$my_cmd`;
}

I am doing something inherently wrong with the above code, but have not been able to figure it out :-(


# Always include these at the top of your programs.
# It will help you find bugs like the ones you had.
use strict;
use warnings;

# You can get all arguments in one shot.
my ($version, $foldername, $outputfile) = @ARGV;

# A flag so we can test our script. When
# everything looks good, set it to 1.
my $RUN = 0;

my $mkdir_cmd = "mkdir -p ~/$foldername";
my $mkdir_out = run_it($mkdir_cmd);

# Word quoting with qw().
my @outputtype = qw(a b c d e f);

# If you already have a list, just iterate over it --
# no need to manually manage the array subscripts yourself.
for my $type (@outputtype) {
    my $my_cmd = "./my_app -v $version -t $type -f $outputfile > ~/$foldername/$type.out";
    my $my_out = run_it($my_cmd);
}

# Our function that will either run or simply print
# calls to system commands.
sub run_it {
    my $cmd = shift;
    if ($RUN){
        my $output = `$cmd`;
        return $output;
    }
    else {
        print $cmd, "\n";
    }
}


The for loop has missing $

The outputtype array is missing a $itr for the index

There may be more -- I haven't tested. This is the obvious stuff.

It looks like maybe you are coming from a language like C where a variable can be a bareword like "i". Variables in perl always start with $ for scalar, @ for list, % for hash.

0

精彩评论

暂无评论...
验证码 换一张
取 消