Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior with eq operator in a perl while loop. while loop does not stop

Tags:

perl

While loop below does not stop after scalar $quit clearly does not equal 'j'. Why won't it stop?

#!/usr/bin/perl -w

use strict;
my $quit = 'j';

while ($quit eq 'j') {

    print "Enter whatever value you want and I bet I still continue.\n";
    chomp (my $quit = <STDIN>);
    print "quit equals: $quit\n";

} 
like image 580
gatorreina Avatar asked Dec 11 '25 14:12

gatorreina


1 Answers

Inside the loop you are creating a new $quit variable with the my keyword:

chomp (my $quit = <STDIN>);

You actually want to assign to the existing variable:

chomp($quit = <STDIN>);

Note that a Perl linting program such as Perl::Critic would have alerted you to this problem:

Reused variable name in lexical scope: $quit at line 9, column 12. Invent unique variable names. (Severity: 3)

like image 176
amon Avatar answered Dec 14 '25 08:12

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!