Hi folks!

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.