in reply to Textfile to csv with a small twist
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Textfile to csv with a small twist
by jZed (Prior) on Aug 25, 2005 at 18:47 UTC | |
by pbeckingham (Parson) on Aug 25, 2005 at 19:12 UTC | |
by jZed (Prior) on Aug 25, 2005 at 19:21 UTC | |
by ChrisR (Hermit) on Aug 25, 2005 at 19:33 UTC | |
by jZed (Prior) on Aug 25, 2005 at 21:21 UTC | |
by ChrisR (Hermit) on Aug 26, 2005 at 12:44 UTC | |
by Bentov (Novice) on Aug 25, 2005 at 19:25 UTC | |
by jZed (Prior) on Aug 25, 2005 at 19:43 UTC | |
by Bentov (Novice) on Aug 25, 2005 at 20:15 UTC | |
by jZed (Prior) on Aug 25, 2005 at 21:17 UTC |