私はPerlを使用してファイルの内容を変更しようとしています。単一ファイルハンドルを使用してファイルの内容を変更する方法
次のスクリプトは正常に動作します。
#!/usr/bin/perl
use strict;
use warnings;
open(FH,"test.txt") || die "not able to open test.txt $!";
open(FH2,">","test_new.txt")|| die "not able to opne test_new.txt $!";
while(my $line = <FH>)
{
$line =~ s/perl/python/i;
print FH2 $line;
}
close(FH);
close(FH2);
test.txt
の内容:
im learning perl
im in File handlers chapter
test_new.txt
での出力:
im learning python
im in File handlers chapter
私はその後、私は、ファイルの内容を変更するために同じファイルハンドルを使用しようとすると期待される出力が得られない。次はこれを実行しようとするスクリプトです:test.txt
で
#!/usr/bin/perl
use strict;
use warnings;
open(FH,"+<","test.txt") || die "not able to open test.txt $!";
while(my $line = <FH>)
{
$line =~ s/perl/python/i;
print FH $line;
}
close(FH);
誤った出力:
im learning perl
im learning python
chapter
chapter
どのように私は、単一のファイルハンドルを使用してファイルの内容を変更できますか? Сухой[email protected]として
実際には、 'perl -i -pe 's/perl/python/i' test.txt'でさえ、別のファイルに書きたいと思うでしょう。あるいは、一度にファイル全体を読んだり、変更したり、ファイル全体を同じハンドルに書き戻したりできます。 –
@Сухой27コマンドでオプションが何をするか説明できます。つまり、-i -pe – kart1657
ハンドラではなくファイル**ハンドル**です。 – melpomene