perl:在第N位写入文件

vrb*_*lgi 5 perl

我正在尝试写入Nth POSITION的档案.我试过下面的例子,但最后写了.请帮助实现这一目标.

#!/usr/bin/perl

open(FILE,"+>>try.txt")
or
die ("Cant open file try.txt");

$POS=5;

   seek(FILE,$POS,0);

   print FILE "CP1";
Run Code Online (Sandbox Code Playgroud)

Cha*_*ens 4

您正在以读写附加模式打开文件。尝试以读写模式打开文件:

my $file = "try.txt";
open my $fh, "+<", $file
    or die "could not open $file: $!";
Run Code Online (Sandbox Code Playgroud)

open另外,请注意三个参数、词法文件句柄 和的使用$!

#!/usr/bin/perl

use strict;
use warnings;

#create an in-memory file
my $fakefile = "1234567890\n";
open my $fh, "+<", \$fakefile
    or die "Cant open file: $!";

my $offset = 5;

seek $fh, $offset, 0
    or die "could not seek: $!";

print $fh "CP1";

print $fakefile;
Run Code Online (Sandbox Code Playgroud)

上面的代码打印:

12345CP190
Run Code Online (Sandbox Code Playgroud)