Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

endless loop while .=

by Anonymous Monk
on Jan 23, 2010 at 13:12 UTC ( [id://819179]=perlquestion: print w/replies, xml ) Need Help??

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 ...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://819179]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-19 10:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found