Pregunta

I am newbie learning perl. The question I have is how do I make sure that if the mine is not set, after the while, I need to send an error or exception?

while (my ($a, $b) = each %$him) {
    if (($c->{$d}) eq $a) {
        $mine = $b;
    }
}

Here I have to return error if $mine is not set.

¿Fue útil?

Solución

That whole while loops is unnecessary. You just need

die if !exists($him->{ $c->{$d} });
my $mine = $him->{ $c->{$d} };

You might prefer

# If doesn't exist or isn't defined
die if !defined($him->{ $c->{$d} });
my $mine = $him->{ $c->{$d} };

or

# If doesn't exist, isn't defined, or is false.
die if !defined($him->{ $c->{$d} });
my $mine = $him->{ $c->{$d} };

Otros consejos

Your whole loop is somewhat strange, because your loop variables $a and $b have nothing to do with the variables $c or $d. Note also that you should not use $a and $b, because they are reserved for the sort function. So, as ikegami says, your loop is entirely redundant, unless you made a typo and meant $b instead of $d.

Assuming $c->{$b} is "the mine" and "not set" means "not defined":

while (my ($a, $b) = each %$him) {
    unless (defined $c->{$b}) {       # the value for this key is undefined
        warn "Undefined mine!";       # produce warning message
        next;                         # skip to next loop iteration
    }
    ....
}

You can also use die which produces a fatal error.

You can use Perl's defined function, as follows:

if (!defined($mine)) {
    # produce error here
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top