Yes, you need a variable that is global to the while loop because you need to preserve some state between iterations of the loop. Consider:

use strict; use warnings; my $inFileStr = <<STR; IM,BEN01,D,0 IM,BEN02,D,0 IM,BEN03, ,0 IM,BEN04, ,0 IM,BEN05, ,0 IM,BEN06,C,0 IM,BEN07, ,0 IM,BEN08, ,0 IM,BEN09, ,0 IM,BEN10,D,0 STR my $first; open my $inFile, '<', \$inFileStr or die "Can't open input file: $!\n" +; while (<$inFile>) { chomp; my @data = split /,/; if ($data[2] =~ /^(D|C)$/) { print " > $first.txt\n" if defined $first; print "type $data[2] "; $first = $data[1]; } print "$data[1].txt "; } close $inFile; print " > $first.txt\n" if defined $first;

Prints:

type D BEN01.txt > BEN01.txt type D BEN02.txt BEN03.txt BEN04.txt BEN05.txt > BEN02.txt type C BEN06.txt BEN07.txt BEN08.txt BEN09.txt > BEN06.txt type D BEN10.txt > BEN10.txt

There are a few things that I've tidied up that you should take note of. First off, always use strictures (use strict; use warnings;). Use the three parameter version of open and check the result (using die is pretty standard for that). Use lexical variables (my $inFile) for file handles. printf is not print - do not confuse them or you will likely have an unhappy life. Regular expressions are clearer (when you get used to them) for non-trivial string matching (see perlretut and perlre).


Perl's payment curve coincides with its learning curve.

In reply to Re: Global vs. Local Variables Assistance Requested by GrandFather
in thread Global vs. Local Variables Assistance Requested by Knoperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.