I am trying to create a script that will take output of a system command and I want to organize the data into an array.
The script is to discover VMs residing on a local ESXi server I have. I am using plink.exe to send the command to the server and then it returns a list of VMs that looks like this.
Vmid Name File Guest OS Version Annota开发者_如何转开发tion 128 NS01 [datastore2] NS01/NS01.vmx ubuntu64Guest vmx-07 144 NS02 [datastore2] NS02/NS02.vmx ubuntu64Guest vmx-07 208 MX01 [datastore2] MX01/MX01.vmx ubuntu64Guest vmx-07 224 SQL01 [datastore2] SQL01/SQL01.vmx ubuntu64Guest vmx-07 240 WS01 [datastore2] WS01/WS01.vmx ubuntu64Guest vmx-07
How would I take this and make an array out of it? The only columns that really matter are VMID, Name, File
The command I am using to get the output is this.
# Parse ESX\ESXi server for virtual machines that reside on it
system ("$plink \-batch \-pw $esx_password $esx_user\@$esx_host vim-cmdvmsvc/getallvms\n");
Any insight would be great.
Yes, use backquotes not system
if you want to parse the output.
my $cmd
= "$plink -batch -pw $esx_password $esx_user\@$esx_host "
. "vim-cmdvmsvc/getallvms"
;
my @lines = `$cmd`;
system
will just use your standard out.
Not sure why you were escaping the dashes, though...
Once you have the output, you can do the following (note that I leveraged the fixed-length fields look):
foreach ( @line ) {
# this is the get-it-and-do-something-else-with-it version
my ( $vmid, $name, $file )
= substr( $_, 0, 47 ) =~ m/^ ( \d+ ) \s+ ( \S+ ) \s+ (.*\S) \s* $/x
;
# OR the store-it-in-an-array-of-hashes version:
@{ my $h = {}}{ qw<VMID Name File> }
= substr( $_, 0, 47 ) =~ m/^ ( \d+ ) \s+ ( \S+ ) \s+ (.*\S) \s* $/x
;
push @array, $h if %$h;
}
If none of the data columns will contain spaces, you could easily split(/\n/)
the output into lines, iterate over those, and split(/\s+/)
the rows into arrays. Then extract the columns you are interested in, by index.
精彩评论