Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I restart a "do-while" loop after breaking out of a foreach loop?

Tags:

perl

I have a small snippet of code from my config script, the idea is the configuration is loaded then each key is checked for the hostname that has been entered. But if a configuration is found to contain the same hostname then it is rejected and displays a warning message that a configruation with that hostname already exists.

The problem is I need the foreach loop that checks for the existance of the hash key to restart the do-while loop so another hostname can be tried or the user can ^C out of the script.

Here is the snippet;

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');

This is what the template hash looks like.

my %template = (
    host => 'undef',
    port => 'undef',
    login => {
        user => 'undef',
        password => 'undef',
    },
    options => {
        snapshots => "0",
        compress => "0",

        # This is expressed as an array
        exclude => 'undef',
    },
);
like image 409
ianc1215 Avatar asked Feb 23 '23 01:02

ianc1215


1 Answers

If there is ever a use for a goto LABEL statement in Perl, this is it.

do {
    START:     # could also go right before the "do"
    ...
    if (...) {
        warn "Configuration exists. Start over.\n";
        goto START;
    }
} while (...);
like image 144
mob Avatar answered Apr 29 '23 20:04

mob