: I 've an output from the system comand as follows.
:
: * /xxx/aaaa /yyy/bbbb
: * /www/cccc /vvv/dddd
: * /uuu/eeee /ttt/ffff
: : : :
:
: I want to parse this output into an array and split them and process each
: entry. Essentially, I want to parse the output of a command to an array and
: process each entry in the array.
:
: My code is
:
: my @vob_list = system ("cleartool lsvob") ;
: foreach $entry (@vob_list) {
: print " This is first '$entry'" ;
: }
You've got a good start on it so far. You just need to use backticks
instead of system(), which doesn't return the output of the command,
and split the line into fields:
my @vob_list = `cleartool lsvob`;
foreach $entry (@vob_list) {
chomp $entry;
my @fields = split /\s+/, $entry;
...
}
For the first line, $fields[0] will contain '*', $fields[1] will
contain '/xxx/aaaa', $fields[2] will contain '/yyy/bbbb', and so on.
(The "chomp" will get rid of the newlines at the end of each line.)
Another way to do it might be to open a pipe to the command and read
the output of that, instead of creating the array beforehand:
open CMD, "cleartool lsvob |" or die "Couldn't open pipe" $!";
while (<CMD>) {
chomp;
my @fields = split;
...
}
close CMD;
My favorite way, especially if the argument to cleartool comes from
outside, would be to open a pipe onto a child process. This one's a
little weird, but because of the way exec() works, it's more secure:
open CMD, "-|" or exec "cleartool", "lsvob";
while (<CMD>) {
chomp;
my @fields = split;
...
}
close CMD;
When you open "-|", Perl automatically forks a child process, which is
what the other side of the "or" will be- in this case, and exec. The
arguments to exec() are passed as a list; when you do that, exec()
won't open a shell to execute the command. So if "lsvob" comes from
outside the program, it will be handled more securely. (Hint: what
will the command do if the argument to "cleartool" is "lsvob; rm *"?)
TIMTOWTDI
--
Tim Kimball · ACDSD / MAST ¦
Space Telescope Science Institute ¦ We are here on Earth to do good to others.
3700 San Martin Drive ¦ What the others are here for, I don't know.
Baltimore MD 21218 USA ¦ -- W.H. Auden