Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!newstop!texsun!convex!convex.COM From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: Why does my variable keep changing?!! Message-ID: <108756@convex.convex.com> Date: 15 Nov 90 00:11:12 GMT References: <27962@sequoia.execu.com> Sender: news@convex.com Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 75 In article <27962@sequoia.execu.com> painter@sequoia.execu.com (Tom Painter) writes: > In the following script, I trying to strip all lines before the first > blankline from stdin. In that vein, I set a flag ($header) to "Y" > and change it to "N" after it hits the blank line. So far it works. > However, when I return to the top of the while loop, $header has been changed > back to "Y". The "N" should last for the rest the time, I never want it > changed back. Soooo, why does it change back? It almost looks as if > the "while" is a little subroutine and it isn't exporting $header globally. > I did run with "-d" and it never returned to line 3 to reset it. > Any help appreciated. > Tom > #! /usr/bin/perl > $header = "Y"; > while (<>) { > print $header; > if ($header = "Y"){ > if (/^$/){ > $header = "N"; > } > next; > } > if (grep(/SOME STRING/,$_)){ > printf " \n"; > } > print; > } That's pretty mangled perl. You're doing several things wrong, like using = for == (or in this case eq), using grep oddly, etc, and you're working far too hard. Your code corrected would be: #!/usr/bin/perl $header = "Y"; while (<>) { print $header; # you'll get a lot of Y's here if ($header eq "Y") { if (/^$/) { $header = "N"; } next; } if (/SOME STRING/) { print " \n"; # don't bother with printf here } print; } But that's still way too complex. #!/usr/bin/perl while (<>) { next if 1 .. /^$/; print "\f\n" if /SOME_STRING/; print; } is one of many ways to express what I think you're trying to do here. You may also set ($/ = '') to read by paragraphs, if that helps. You could also have a variable in your loop like this: $in_header = 1 .. /^$/; See the perl man page on the scalar ".." operator for details. --tom