#!/usr/bin/perl use strict; use warnings; use Text::CSV; use Text::Wrap; $Text::Wrap::columns=100; my $file = "test.txt"; my @line_list; #list of csid on each line, contains duplicates my @csid_list; #list of unique csids #my $oldcsid = 0; my $csv = Text::CSV->new or die "Cannot use CSV: ".Text::CSV->error_diag (); open (my $fh, '<', "$file") or die "Cannot open $file: $!"; $csv->getline ($fh); #skip header row while ( my $row = $csv->getline( $fh ) ) { push @line_list, $row->[0]; } @csid_list = sort {$a <=> $b} uniq(@line_list); # Adds title to each file foreach my $csid (@csid_list) { open (my $csid_fh, '>>', "$csid.txt"); print $csid_fh "####################\n\nCalYouth Case ID: $csid\n\n####################"; close $csid_fh; } close $fh; my $csv2 = Text::CSV->new or die "Cannot use CSV: ".Text::CSV->error_diag (); open (my $fh2, '<', "$file") or die "Cannot open $file: $!"; $csv2->getline ($fh2); # Prints notes to correct csid file my $counter = 1; #counts iterations through loop while ( my $row = $csv2->getline($fh2)) { foreach my $csid (@csid_list) { if ($row->[0] == $csid) { if ($row->[5]) { my $temp_string = wrap("\t","\t","$row->[5]"); #wrap() is from Text::Wrap open (my $csid_fh, '>>', "$csid.txt"); print $csid_fh "\n\n\t------------------------------\n\nNote Entry $counter:\n\n$temp_string\n\n"; #$counter should count each note in a file ++$counter; #increments $counter close $csid_fh; } else { next; } } } } # Sorts out duplicates from an array sub uniq { my %seen; grep !$seen{$_}++, @_; } #More experimental code. Sigh. #Reset the counter for new files #if (-e "$csid.txt"){ # $counter++; # print "$csid.txt exists $counter \n"; #}else{ # $counter=0; #} #Experimental code to handle counter resets. Isn't working. #if ($oldcsid == 0){ # $oldcsid = $csid; # $counter++; #} #elsif ($oldcsid == $csid) { # $counter++; #} #else{ #$counter = 1; Endif for ($row->[0] == $csid). I think this will never be false, except on a blank line, which an output file probably won't have, unless data export >1000 chars. However, removing this check broke stuff. #$oldcsid = $csid; #}