in reply to Elegant Way of Inserting Text at the Start of the File
The code above uses a fixed amount of memory, independent of the size of the file. You may want to do add a loop around syswrite if you think it may not write the entire chunk at once.use Fcntl ':seek'; my $file_name = "..."; my $buffer = <<'EOT'; echo hello echo world echo I'm done. EOT open my $fh, "+<", $file_name or die $!; my $r = 4096; while ($r = sysread $fh, $buffer, $r, length $buffer) { seek $fh, -$r, SEEK_CUR or die $!; syswrite $fh, substr $buffer, 0, $r, "" or die $!; } die $! unless defined $r; syswrite $fh, $buffer or die $!; close $fh or die $!;
|
|---|