in reply to Splitting file into separate files based on record lengths and identifiers

Thank-you, I will try that.

This is what I've tried to date, with help to build the if clauses with expressions, but as soon as I removed the first $ record it broke, and I'm still none the wiser as to why

#!/usr/bin/perl use strict; use warnings; open my $data_fh, '<', 'data.txt' or die "could not open data.txt: $!\ +n"; open my $dollar_fh, '>', 'dollar.txt' or die "could not open dollar.tx +t: $!\n"; open my $star_fh, '>', 'asterisk.txt' or die "could not open asterisk. +txt: $!\n"; open my $percent_fh, '>', 'percent.txt' or die "could not open dollar. +txt: $!\n"; while( <$data_fh> ){ chomp; while( length ){ if( s{ (\d+) \$ }{}msx ){ my $len = $1; my $data = substr( $_, 0, $len, '' ); print $dollar_fh "$data\n" or die "could not print to dollar.txt +: $!\n"; } if( s{ (\d+) \* }{}msx ){ my $len = $1; my $data = substr( $_, 0, $len, '' ); print $star_fh "$data\n" or die "could not print to asterisk.txt +: $!\n"; } if( s{ (\d+) \% }{}msx ){ my $len = $1; my $data = substr( $_, 0, $len, '' ); print $percent_fh "$data\n" or die "could not print to percent.t +xt: $!\n"; } } } close $dollar_fh or die "could not close dollar.txt: $!\n"; close $star_fh or die "could not close asterisk.txt: $!\n"; close $percent_fh or die "could not close percent.txt: $!\n"; close $data_fh or die "could not close data.txt: $!\n";
Thanks!
  • Comment on Re: Splitting file into separate files based on record lengths and identifiers
  • Download Code

Replies are listed 'Best First'.
Re^2: Splitting file into separate files based on record lengths and identifiers
by kennethk (Abbot) on Aug 25, 2010 at 21:58 UTC
    Thank you for posting code - now I better understand your coding abilities and can give you specific critiques. I ran your code, as posted, against your posted sample input and it seems to have functioned as per spec. What makes you think it broke?

    As a side note, there is no need to explicitly close your files. Since you've used Indirect Filehandles, Perl with automatically clean those up once the variables got out of scope.

      This is the data that breaks my original script:

      0002*330004%19770004$BOB 0002*430004%1967

      ...it results in spitting this into the dollar.txt file and nothing into the other two.

      0002*330004%BOB 0002*430004%1967

      Thanks!