views:

110

answers:

2

I am writing a Perl script which does this :

  1. Reads the values of the environment variables a to z in a loop.
  2. Depending on the value of the environment variables, generates a result file similar to

    a - 1,2,3,4
    b - a,b,c
    c - $234.34,$123.12
    keyword1 %a%
    keyword2 %b%
    keyword3 %c%
    

    The point to note is that all the declarations have to come before the usages.

  3. The problem is that for example I read a, and generate this result file

    a - 1,2,3,4
    keyword3 %c%
    

    Now when I read b , I need the result file to look like this

    a - 1,2,3,4
    b - a,b,c
    keyword1 %a%
    keyword2 %b%
    

How should I do this using Perl?

One way I can think of is to generate two different files - one with the declarations and other with the usages, and then concatenate the files at the end of execution of the script.

Is there a better way?

+5  A: 

No need for separate files. Accumulate the declarations and usages in two different array variables, @declarations and @usages. After you've read all your environment variables and determined the contents of the two arrays, print them:

say for @declarations;
say for @usages;

You might even be able to omit the first array. Once you figure out what a declaration should be, print it out immediately. You only need to accumulate the usages until you know there will be no more declarations.

Rob Kennedy
Thanks @Rob, arrays are a good choice, and are definitely better than having to create two separate files and concatenating.
Lazer
@Lazer: I think this was the point of all the commenters above -- what is the purpose of the output -- why output to files at all?
Ether
@Ether, evidently, Lazer's script is generating code to be executed later by some other interpreter. I don't see why there's so much resistance to the idea of having a Perl script whose purpose is to create a file.
Rob Kennedy
@Rob: having a script create a file which is just going to be processed again by another script implies that the two scripts could be combined.
Ether
+1  A: 
use strict;
use warnings;

my @keys = sort keys %ENV;
print "$_ - $ENV{$_}\n" foreach @keys;
my $kwcnt = 1;
print "keyword${ \( $kwcnt++ ) } \%$_\%\n" foreach @keys;

I sort the keys once, and run through them twice.

Axeman