Is it safe to insert a foreach loop into another foreach loop
I am wanting to add the ability for my concept scr开发者_开发技巧ipt to iterate the same loop of commands over a list of servers, rather that over just one server.
Is it safe to have a foreach loop inside of a foreach loop. Or is there another way to do this?
# Create an empty hash table for discovered virtual machines
my %virtual_machines = ();
my @getallvms = $ssh1->capture('vim-cmd vmsvc/getallvms');
# Remove first line from ESX\ESXi output
shift @getallvms;
# Collect data from ESX\ESXi output
foreach my $server (@servers) {
foreach my $vm (@getallvms) {
# Match ID, NAME and VMX file name
$vm =~ m/^(?<ID> \d+)\s+(?<Name> \S+)\s+\[.+?\]\s+.+?\/(?<VMX> .+?\.vmx)/xm;
my $id = "$+{ID}";
my $name = "$+{Name}";
# Find the absolute path to the VMX file for each virtual machine
my $vmx_location = $ssh1->capture("find -name $+{VMX}");
}
}
That is a piece of my script and the basic concept I want to achieve as per the first response.
Yes, it's safe. However, you will probably want to use different loop variables other than the default $_
.
foreach my $server (@servers) {
foreach my $command (@commands) {
# ...
}
}
Yes. This is fairly common in any language.
Sure, it is safe. If you want, you can wrap your inner set of commands into a method and then have the outer foreach loop call that method. That at least makes your code a little more readable.
There's nothing technically wrong with using nested loops, but for the sake of efficiency, you might want to experiment with hashes or find ways to organize your data so that the highest probability hits are organized toward the top of the lists.
Do you have an example of what you're doing?
As the other answers have already assured you, yes, it's perfectly save to use nested loops.
You may want to label them, though, this is especially useful if you use next
or last
to break out of any of the loops. (If you need to break out of any other loop than the innermost one, you have to use labels.)
Example:
SERVER:
foreach my $server (@servers) {
VM:
foreach my $vm (@getallvms) {
next VM if (whatever);
last SERVER if (whatever);
}
}
See perldoc.
精彩评论