perl while循环 - 仅在第一次满足条件时退出

时间:2014-10-16 18:11:43

标签: perl while-loop

我有一个脚本,它有多个3 if语句,具体取决于" case"因改变将要进行的计算。我刚刚开始学习perl,我认为问题是我的最后一个输入不是while块的一部分,但是我无法弄清楚如何将其保持在里面而不会出现花括号错误

 [flata@localhost bin]$ casespacked.pl
 Please enter your name: done
 [flata@localhost bin]$ casespacked.pl
 Please enter your name: bill
 Please enter pay rate: 10
 Please enter hours worked: 20
 Please enter cases packed: 4
 Name: bill, Hours: 20, Regular Pay: 200, Bonus Pay: 20, Total Pay: 220
 Please enter your name: done
 Please enter pay rate:^C

循环可以正常工作,并且会继续产生我需要的结果但是它不会正确退出,只有当你第一次输入完成时才会输入你的名字

#!/usr/bin/perl
print "Please enter your name: ";
chop( my $Name = <stdin> );
while ( $Name ne "done" ) {
    print "Please enter pay rate: ";
    chop( my $Rate = <stdin> );
    print "Please enter hours worked: ";
    chop( my $Hours = <stdin> );
    print "Please enter cases packed: ";
    chop( my $Cases = <stdin> );
    if ( $Cases >= 1 && $Cases <= 9 ) {
        $Bonus = ( $Cases * 5 );
        $Pay   = ( $Rate * $Hours );
        $Total = ( $Bonus + $Pay );
    }
    if ( $Cases >= 10 && $Cases <= 20 ) {
        $Bonus = ( $Cases * 8 );
        $Pay   = ( $Rate * $Hours );
        $Total = ( $Bonus + $Pay );
    }
    if ( $Cases >= 20 ) {
        $Bonus = ( $Cases * 10 );
        $Pay   = ( $Rate * $Hours );
        $Total = ( $Bonus + $Pay );
    }
    {
        print "Name: $Name, Hours: $Hours, Regular Pay: $Pay, Bonus Pay: $Bonus, Total Pay: $Total\n";
    }
    print "Please enter your name: ";
    chop( my $Name = <stdin> );
}

即使我移动了印刷品,请输入您的姓名:&#34 ;;所以它在最后一个if语句之后,它不会退出哪个应该仍然在while循环中?或者我不理解

2 个答案:

答案 0 :(得分:4)

您的错误是由于您阅读后续的$Name词法作用于while块,然后在while (COND)中进行测试之前恢复到之前的值:

    chop( my $Name = <stdin> );
} # $Name reverts to previous value

这将解决您当前的错误。

但是,我想提出一些其他的建议:

  • 始终在每个Perl脚本的顶部包含use strict;use warnings;

  • 不要试图将你的条件直接绑定到while循环,而只是使用一个无限循环,而不使用last

  • 使用chomp代替chop

  • 将全部小写用于变量名称。请阅读perlstyle了解具体信息。

  • 关联条件后,请使用ifelsifelse代替独立的if链。如果您随后重新排序条件,则可以检查某些内容是否大于,这简化了您的逻辑。

以下演示了这些和其他修复:

#!/usr/bin/perl
use strict;
use warnings;

while (1) {
    print "Please enter your name: ";
    chomp( my $name = <STDIN> );

    last if $name eq "done";

    print "Please enter pay rate: ";
    chomp( my $rate = <STDIN> );

    print "Please enter hours worked: ";
    chomp( my $hours = <STDIN> );

    print "Please enter cases packed: ";
    chomp( my $cases = <STDIN> );

    my $bonus;

    if ( $cases >= 20 ) {
        $bonus = $cases * 10;

    } elsif ( $cases >= 10 ) {
        $bonus = $cases * 8;

    } elsif ( $cases >= 1 ) {
        $bonus = $cases * 5;

    } else {
        warn "Invalid number of Cases: $cases\n";
        next;
    }

    my $pay   = $rate * $hours;
    my $total = $bonus + $pay;

    print "Name: $name, Hours: $hours, Regular Pay: $pay, Bonus Pay: $bonus, Total Pay: $total\n";
}

答案 1 :(得分:1)

您正在使用my $Name创建一个新变量,屏蔽前一个变量。从最后一个作业中删除my,它将开始工作。