开发者

Is there a better way to achieve this using Perl? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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 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.

  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?


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜