Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks, consider the following code

#!/usr/bin/perl use warnings; use strict; my $content; open(IN, "<", $ARGV[0]) or die $!; while ( $content .= <IN> ) { print $content; }; close(IN) or die $!;

Can someone explain in laymans words why .= causes an endless while loop?

Replies are listed 'Best First'.
Re: endless loop while .=
by almut (Canon) on Jan 23, 2010 at 13:28 UTC

    ...because $content is accumulating the input. In other words, it isn't empty/false when the while loop has reached the end of the input, so the while loop keeps running.

      Thank you.

Re: endless loop while .=
by Marshall (Canon) on Jan 23, 2010 at 13:42 UTC
    See explanation by almut - while() is testing true/false of the statement, not status of <IN>. Here is small mod to your code that avoids the problem.
    #!/usr/bin/perl use warnings; use strict; my $content; open(IN, "<", $ARGV[0]) or die $!; while ( <IN> ) { print $content.= $_; }; close(IN) or die $!;
Re: endless loop while .=
by apl (Monsignor) on Jan 23, 2010 at 13:26 UTC
    You can always append a Null ...