This will handle missing fields in certain records. Perl will issue a warning however if a field is missing.#!c:\perl\bin\perl -w use strict; my $currentheading; my %hash; my @headings; my @array; open(FILE,"c:\\test.txt"); while(my $line = <FILE>) { chomp($line); if($line =~ /(.*?:)$/) { $currentheading = $1; push @headings, $currentheading; } else { push @{$hash{$currentheading}}, $line; } } for my $x(0..$#headings) { my $record = 0; for my $y(0..$#{$hash{$headings[$x]}}) { $array[$record][$x] = $hash{$headings[$x]}[$y]; $record++; } } my $header = join ",",@headings; print "$header\n"; for my $x(0..$#array) { my $recordline = join ",", @{$array[$x]}; print "$recordline\n"; }
Note: I removed the newlines to show the data in an easily readable format. To keep them just remove the line: chomp($line);
Update:looks like pbeckingham beat me to a similar solution.
In reply to Re: Textfile to csv with a small twist
by ChrisR
in thread Textfile to csv with a small twist
by Bentov
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |