Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

perl - input to the program with all the strings in an array one by one

I have a shell script consisting of so many perl scripts, one of the perl script have to be run with differnt input each time and the value has to be stored in a single file at the end as shown

 #!/bin/sh
 .....
 ....
 perl test.pl apple
 perl test.pl mango
 perl test.pl banana
 ... 
... 
....

I type these names in command lines by looking at the file generated with these names.

**names.txt**
apple
mango
banana

OR

**names.txt**
    apple    mango   banana

Is their a way in perl or shell which takes each name at a time as an input.
That is can names.txt be considered as an array and then the perl script take each array value at a time as an input using ARGV or any other means.So that i can have my shell script like

#!/bin/sh
     .....
     ....
     perl test.pl names.txt
     .... 
    ... 
    ....
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual way to write perl programs that take input from files is to construct them as follows:

while ($line = <>) {

    # do stuff with $line
}

If filenames are given on the command line, perl will automatically open them one by one, feeding the lines to your script. If no filenames are given, it will read from standard input.

But if you write your script this way, you won't be able to give it fruits directly on the command line, they will have to be in a file or standard input.

To handle multiple fruit on the same line, your code can do:

while (my $line = <>) {

    chomp $line;

    foreach my $fruit ( split ' ', $line ) {

        # do something with $fruit
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...