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

I'm writing a script which will:
1. Generate arguments to be passed to another program.
2. Run the second program with arguments.
3. Write the output to the current directory.

Here is an example of the input to the script:

cat1-dd1 as boston1-nta1 peer 10
dog1-dd1 as philly-snta1 peer 10
bird-dd1 as philly-snta1 peer 10
fish-dd1 as boston1-nta1 peer 10

Heres the code:
#!/usr/local/bin/perl -w use strict; my $config = $ARGV[0]; my $date = $ARGV[1]; my $program = "animals"; my $matrix = "netmatrix"; my $path = "path"; my %hash; my $host; my $key; die "Usage: $0 path-to-config-file yyyymmdd\n" unless @ARGV == 2; open (CONFIG, $config) || die "Cannot open $config_file:$!\n"; while (my $line = <CONFIG>) { chomp $line; next if ($line =~ /^\#/); my ($router, $cache, $nta, $as, $Sample) = split (' ', $line); $host = (split "-", $nta)[0]; $host =~ tr/0-9//d; $hash{$router}=$host; } foreach $key (keys %hash) { print "$program $hash{$key} $matrix $path/CISCO_$key.clean"; ####I'll execute the program here, once this is figured out }
Which produces the following output:

animals boston netmatrix path/CISCO_fish-dd1.clean
animals philly netmatrix path/CISCO_dog1-dd1.clean
animals philly netmatrix path/CISCO_bird-dd1.clean
animals boston netmatrix path/CISCO_cat1-dd1.clean

What I want to do is test for the existence a duplicate key value, and if so, append $path/CISCO_$key.clean to the end of the statement:

animals philly netmatrix path/CISCO_dog1-dd1.clean path/CISCO_bird-dd1.clean
animals boston netmatrix path/CISCO_fish-dd1.clean path/CISCO_cat1-dd1.clean

Can anyone help out?

Replies are listed 'Best First'.
Re: Append Logic
by danger (Priest) on Jan 31, 2001 at 02:36 UTC

    Looks to me like you're keying the hash on the wrong data -- I think you'd have an easier time if you keyed your hash on $host and stored an array of $router's for each host.

    So your hash assignment would like this:

    push @{$hash{$host}}, $router;

    And your current foreach loop would then be:

    foreach $key (keys %hash) { print "$program $key $matrix "; print "$path/CISCO_$_.clean " for @{$hash{$key}}; print "\n"; }
      Thanks! The only thing I dont know how to do is actually execute each line of output as an individual command.
        You can use system, or open, or backticks, or qx//. Depending on what you want, perlfaq8 has a question entitled How can I capture STDERR from an external command? that has more information than you need to answer this question.

        The appropriate answer depends on many things. Do you want to capture the output? Do you want just the exit code? Do you want to pass extra commands while the program executes?