in reply to Global vs. Local Variables Assistance Requested
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).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Global vs. Local Variables Assistance Requested
by Knoperl (Acolyte) on Dec 04, 2008 at 23:03 UTC |