I have a bunch of files, each containing records which are 320 characters in length. The records are supposed to be separated by CRLFs, but some of the files are missing the CRLFs completely. My task is to find the bad files and fix them. Here's the code I came up with:
for my $file ( @files ) { open IN, "$file" or die "Can't open $file!"; my $count = 0; $count += tr/\n// for (<IN>); if ( !$count) { open OUT, ">$file.new" or die "Can't open $file.new for output!"; seek IN, 0, 0; while ( <IN> ) { s/(.{320})/$1\n/g; print OUT; } } }
This seems to work, but I'm not crazy about the solution. The s/// wasn't intuitive to me, but it was the first solution I found (after trying to find something using seek and/or unpack). This wouldn't work if the file already contained newlines, and I wanted to insert some other character at regular increments. I'm also concerned that I might run into problems with greediness or globalness in the s///.
Can anyone suggest a more flexible or Perlish approach to the problem of inserting string x at increment n? This seems like it would be in the FAQ, but I couldn't find it. If it is, my apologies!
Peter
In reply to Insert at regular increments by EyeOpener
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |