Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

my $a =10;
my $b =200;
my $c,$d;
goto UP if ($a > 20);
$d = $c + $b;
print "$d
";
UP:
$c = $b -$a;
print "$c
";

The above statements inside the label executes even if the condition fails.

question from:https://stackoverflow.com/questions/65840373/the-statements-inside-the-label-executes-even-if-the-condition-fails-can-anyone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
765 views
Welcome To Ask or Share your Answers For Others

1 Answer

It seems like you are mixing up how the labels and goto work. In fact, goto should never be used for flow control. It's really confusing.

This is how your code runs at the moment:

enter image description here

As you can see, the last two statements (those are after your UP label) are always executed. Perl will check the condition, and if it is true, skip ahead. If the condition is false, it runs the two statements following immediately, and then runs the label and the rest.

Labels don't make subroutines in Perl. They just give a line a name. The line of code is still executed normally.

If you want to do one or the other instead, you need an if-else construct. That's done like this in Perl.


my $a = 10;
my $b = 200;
my ( $c, $d );
if ($a > 20) {
    $c = $b -$a;
    print "$c
";
} else {
    $d = $c + $b;
    print "$d
";
}

Since you seem to insist on goto, you can make that work, but you need to tell it to stop execution.

my $a =10;
my $b =200;
my $c,$d;
goto UP if ($a > 20);
$d = $c + $b;
print "$d
";
exit;  # <------------- this stops execution and ends the program
UP:
$c = $b -$a;
print "$c
";

Of course your code won't do much, because both $c and $d are undef.

You should really turn on use strict and use warnings, and fix the problems both of these pragmata will show you.

Also note that $a and $b are reserved variables to be used inside sort.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...