I am writing a Perl script which does this :
- Reads the values of the environment variables
a
toz
in a loop. Depending on the value of the environment variables, generates a result file simila开发者_运维技巧r 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.
The problem is that for example I read
a
, and generate this result filea - 1,2,3,4 keyword3 %c%
Now when I read
b
, I need the result file to look like thisa - 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?
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.
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.
精彩评论