Welcome to the monastery.
First, rather that iterating over the file 4 times (possible, but inefficient -- see seek), I would suggest pulling in all the data in one loop, and then processing it in a second loop. My experience has always been the first step to understanding how to deal with data is knowing what kind of file structure to use. You could store the lines of the file in an array, or you could use an array of arrays and then traverse that data structure later. Since you have your labels, maybe something like:
use strict;
use warnings;
my @labels = ('fee', 'fi', 'fo', 'fum');
open(my $fh, '<', "folks.txt") || die "can't open folks: $!";
my @list;
while (<$fh>) {
chomp;
push @list, [split /,/];
}
for my $element (@list) {
print "$labels[0],$element->[0],$element->[1]\n";
}
for my $element (@list) {
print "$labels[1],$element->[0],$element->[2]\n";
}
for my $element (@list) {
print "$labels[2],$element->[0],$element->[3]\n";
}
for my $element (@list) {
print "$labels[3],$element->[0],$element->[4]\n";
}
or, a little better:
use strict;
use warnings;
my @labels = ('fee', 'fi', 'fo', 'fum');
open(my $fh, '<', "folks.txt") || die "can't open folks: $!";
my @list;
while (<$fh>) {
chomp;
push @list, [split /,/];
}
for my $i (0 .. 3) {
for my $element (@list) {
print "$labels[$i],$element->[0],$element->[$i+1]\n";
}
}
or maybe even
use strict;
use warnings;
my @labels = ('fee', 'fi', 'fo', 'fum');
open(my $fh, '<', "folks.txt") || die "can't open folks: $!";
my @list;
while (<$fh>) {
chomp;
my @line = split /,/;
my %hash = (number => shift @line);
for my $i (0 .. $#labels) {
$hash{$labels[$i]} = $line[$i];
}
push @list, \%hash;
}
for my $label (@labels) {
for my $element (@list) {
print "$label,$element->{number},$element->{$label}\n"
}
}
Second, please note I added some use statements at the top of the script. Read Use strict warnings and diagnostics or die to learn why. I also swapped to a 3-argument open with an indirect file handle. Especially if you are just learning, good habits to develop.
Third, rather than rolling you own, try using CPAN. In particular, for dealing with CSV, try Text::CSV. Did you know CSV files contain escaping sometimes? Text::CSV does, and it's tested.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|