Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

perl - The statements inside the label executes even if the condition fails.Can anyone explain what I'm doing here wrong?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...