我的配置脚本中有一小段代码,想法是加载配置然后检查每个密钥是否输入了主机名.但是,如果发现配置包含相同的主机名,则会被拒绝,并显示一条警告消息,指出已存在具有该主机名的配置.
问题是我需要foreach循环检查散列键的存在以重新启动do-while循环,以便可以尝试另一个主机名或者用户可以^C不在脚本中.
这是片段;
my $host;
do {
print "Enter the hostname or IP of the ESXi server: ";
chomp($host = <STDIN>);
if ($host eq '') {
print "You must enter a hostname or IP address!\n";
} elsif ($host ne '') {
# We need to catch duplicate configurations for we don't do the same work twice
foreach (keys %config) {
if ($config{$_}{host} ne $host) {
last;
} elsif ($config{$_}{host} eq $host) {
warn "Configuration for $host already exists!\n";
}
}
if ($ping_obj->ping($host)) {
$config{$config_tag}{host} = $host;
} elsif (! $ping_obj->ping($host)) {
print RED . "Ping test for \'$host\' failed" . RESET . "\n";
}
$ping_obj->close();
}
} while ($config{$config_tag}{host} eq 'undef');
Run Code Online (Sandbox Code Playgroud)
这就是模板哈希的样子.
my %template = (
host => 'undef',
port => 'undef',
login => {
user => 'undef',
password => 'undef',
},
options => {
snapshots => "0",
compress => "0",
# This is expressed as an array
exclude => 'undef',
},
);
Run Code Online (Sandbox Code Playgroud)
如果goto LABEL在Perl中有一个语句的用法,就是这样.
do {
START: # could also go right before the "do"
...
if (...) {
warn "Configuration exists. Start over.\n";
goto START;
}
} while (...);
Run Code Online (Sandbox Code Playgroud)