in reply to Insert at regular increments

Instead of a s/// you could use a simple substr()
substr($_, 321, 1) = "\n"
substr() is the closest thing to referencing strings by index in perl (esp. thanks to it's lvalueability).
HTH

_________
broquaint

Replies are listed 'Best First'.
Re: Re: Insert at regular increments
by EyeOpener (Scribe) on Jul 22, 2002 at 21:06 UTC
    Thanks. I didn't know you could use substr as an lvalue, that's very handy. One comment: I think I'd need to say

    substr($_, 321, 0) = "\n"

    to avoid replacing some poor unsuspecting character with the newline.

    And one question: how would I use this approach to add newlines after every record in the file (i.e. after every 320 characters)?

      how would I use this approach to add newlines after every record in the file (i.e. after every 320 characters)?
      Take advantage of the $/ variable
      { open(my $data, '<', "data_file") or die("ack - $!"); open(my $out, '>', "out_file") or die("ack - $!"); local $/ = \320; while(<$data>) { chomp; print $out $_ . "\n"; } }

      HTH

      _________
      broquaint

        Using $/ is a nice esoteric idea requiring the person to really know perl in order to understand the code... but it won't work unless you already know that the file doesn't have the record separators. (In which case you wouldn't need chomp().) If I read the question correctly, the records themselves are 320 characters, not 319 characters plus a newline. If the file already has newlines, the first newline will become the first character in the second record and everything will get even more squirrely after that.

        If you are going to use it, besides pre-determining the existence of newlines, I suggest use English; and $INPUT_RECORD_SEPARATOR as well as comments explaining the magic for the uninitiated.

        -sauoq
        "My two cents aren't worth a dime."
        
        That's what I was looking for! I knew there was nice native support for dealing with fixed-length records. Much reading to do... Thanks broquaint!