in reply to Parsing a file and splitting into multiple files
#!/usr/bin/perl use warnings; use strict; open my $F, '<', 'file' or die "Cannot open 'file' $!"; open my $H, '>', 'header' or die "Cannot open 'header' $!"; open my $D, '>', 'data' or die "Cannot open 'data' $!"; open my $Q, '>', 'questionaire' or die "Cannot open 'questionaire' $!" +; my %data; while ( <$F> ) { chomp; my ( $type, @fields ) = split /\^/, $_, -1 or next; if ( $type == 1 || $type == 8 ) { print { $type == 1 ? $H : $Q } join( '|', @fields ), "\n"; } elsif ( $type == 2 || $type == 3 || $type == 4 ) { $data{ $fields[ 0 ] }[ $type % 3 ] = [ @fields[ 1 .. $#fields +] ]; } if ( ( eof && %data ) || %data && $type != 2 && $type != 3 && $typ +e != 4 ) { my ( $key, $val ) = %data; print $D join( '|', $key, map defined() ? @$_ : (), @$val ), " +\n"; %data = (); } }
|
|---|