in reply to While loop conditions in Perl

A more perlish way to do this, and the way that confines your variable to the scope of the loop, is like this:

while( my $nextline = <IN> ){ chomp; last unless $nextline eq ''; # exits the loop unless empty line print "Nextline is empty\n"; } # now $nextline goes out of scope

UPDATE: Yes, as cheekuperl noticed, that should be chomp $nextline;

Aaron B.
Available for small or large Perl jobs; see my home node.

Replies are listed 'Best First'.
Re^2: While loop conditions in Perl
by cheekuperl (Monk) on Jul 18, 2012 at 22:09 UTC
    I was wondering if chomp statement in your code should be like :
    chmop $nextline; #chomp uses $_ by default

      Well I actually don't use chomp anymore, I can't really explain it but I have come across files that just didn't agree with chomp. So I use...

      $string =~ s/^\s+//; $string =~ s/\s+$//;

      To remove any whitespace(including newlines) before the first character and after the last character on the line, as well as...

      @fi = split(/\s+/, $nextline);

      ... to break apart the line by spaces.

      This whole issue I was having actually initiated with my while loop being constructed with...

      while(@fi[0] eq'') { $nextline = readline<IN>; //remove whitespace //split the line, but I think I included my accidentally so that +I had my @fi = split..... }

      ...so that I also changed my scope inside the while loop accidentally by using...

       my $nextline = ...

      instead of...

       $nextline = ...
        Thats alright my friend. You could've said it all in one line :)
        I can't really explain it but I have come across files that just didn't agree with chomp
        Now this has made me curious! Could you please elaborate?
        (This might help me if I come across any such situation and I have no clues about what's going on)
        I believe you have probably encountered line feeds followed by new lines ( \r\n ). In this case, just adjust the input record separator ( local $/ = "\r\n"; )