读取和写入perl中的文件

Daa*_*ish 1 perl file-io

    this
    is just
    an example.
Run Code Online (Sandbox Code Playgroud)

让我们假设上面是out.txt.我想读取out.txt并写入同一个文件.

    <Hi >
    <this>
    <is just>
    <an example.>
Run Code Online (Sandbox Code Playgroud)

修改了out.txt.我想在某些行的开头和结尾添加标签.因为我将多次读取该文件,所以每次都无法将其写入不同的文件.

编辑1 我尝试使用,"+<"但它给出了这样的输出:

Hi
this
is just
an example.
<Hi >
<this>
<is just>
<an example.>
 **out.txt**
Run Code Online (Sandbox Code Playgroud)

编辑2 代码参考:

open(my $fh, "+<", "out.txt");# or die "cannot open < C:\Users\daanishs\workspace\CCoverage\out.txt: $!";
     while(<$fh>)
     {
        $s1 = "<";
        $s2 = $_;
        $s3 = ">";
        $str = $s1 . $s2 . $s3;
        print $fh "$str";
     }
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 8

你想要做的事情的想法是有缺陷的.该文件以

H  i  /  t  h  i  s  /  ...
Run Code Online (Sandbox Code Playgroud)

如果你要在适当的位置更改它,在处理第一行后它将如下所示:

<  H  i  >  /  i  s  /  ...
Run Code Online (Sandbox Code Playgroud)

注意你是如何破坏"th"的?您需要制作文件的副本,修改副本,用副本替换原件.

最简单的方法是在内存中制作此副本.

my $file;
{ # Read the file
   open(my $fh, '<', $qfn)
      or die "Can't open \"$qfn\": $!\n";
   local $/;
   $file = <$fh>;
}

# Change the file
$file =~ s/^(.*)\n/<$1>\n/mg;

{ # Save the changes
   open(my $fh, '>', $qfn)
      or die "Can't create \"$qfn\": $!\n";
   print($fh $file);
}
Run Code Online (Sandbox Code Playgroud)

如果您想使用磁盘:

rename($qfn, "$qfn.old")
   or die "Can't rename \"$qfn\": $!\n";

open(my $fh_in, '<', "$qfn.old")
      or die "Can't open \"$qfn\": $!\n";
open(my $fh_out, '>', $qfn)
      or die "Can't create \"$qfn\": $!\n";

while (<$fh_in>) {
   chomp;
   $_ = "<$_>";
   print($fh_out "$_\n");
}

unlink("$qfn.old");
Run Code Online (Sandbox Code Playgroud)

使用技巧,上面的内容可以简化为

local @ARGV = $qfn;
local $^I = '';
while (<>) {
   chomp;
   $_ = "<$_>";
   print(ARGV "$_\n");
}
Run Code Online (Sandbox Code Playgroud)

或者作为一个单行:

perl -i -pe'$_ = "<$_>"' file
Run Code Online (Sandbox Code Playgroud)


小智 5

读取内存中的内容,然后在写入文件时准备所需的字符串。(SEEK_SET 为零不是字节是必需的。

#!/usr/bin/perl

open(INFILE, "+<in.txt");
@a=<INFILE>;
seek INFILE, 0, SEEK_SET ;
foreach $i(@a)
{ 
    chomp $i;
    print INFILE "<".$i.">"."\n";
}
Run Code Online (Sandbox Code Playgroud)

如果您担心内存中读取的数据量,您将不得不创建一个临时结果文件,最后将结果文件复制到原始文件。