2017-10-06 24 views
2

我寫在Perl腳本,我創建一個文件,並獲得來自用戶對文件的輸入,但是當我複製該文件到其他位置的文件被複制但它只是空的。我的代碼是Perl的複製從一個位置文件等,但內容不是抄襲

# !/usr/bin/perl -w 
for($i = 1;$i<5;$i++) 
{ 
    open(file1,"</u/man/fr$i.txt"); 
    print "Enter text for file $i"; 
    $txt = <STDIN>; 
    print file1 $txt; 
    open(file2,">/u/man/result/fr$i.txt"); 
    while(<file1>) 
    { 
    print file2 $_; 
    } 
    close(file1); 
    close(file2); 
} 

fr1到fr4正在創建,但這些都是空的。就像當我運行我的代碼時,它要求輸入我提供的輸入和代碼運行沒有錯誤,但仍然是空的文件。請幫忙。 in line number 4我將<更改爲>也如我以爲創建新文件,它可能需要,但它仍然無法正常工作

+0

你打開'file1' for _reading_(用'<...'),但你寫信給它...? – zdim

+0

我改變了一個寫作還但仍不能正常工作 –

+0

你想要做什麼:(1)打開現有的文件進行讀取,並將其複製到另一個 - 或 - (2)打開,無法寫入新文件,寫信給它,然後將它複製到另一個...? – zdim

回答

4

您需要關閉寫入的文件句柄以便能夠讀取該文件。

use warnings; 
use strict; 
use feature 'say'; 

for my $i (1..4) 
{ 
    my $file = "file_$i.txt"; 
    open my $fh, '>', $file or die "Can't open $file: $!"; 

    say $fh "Written to $file"; 

    # Opening the same filehandle first *closes* it if already open 
    open $fh, '<', $file or die "Can't open $file: $!"; 

    my $copy = "copy_$i.txt"; 
    open my $fh_cp, '>', $copy or die "Can't open $copy: $!"; 

    while (<$fh>) { 
     print $fh_cp $_; 
    } 
    close $fh_cp; # in case of early errors in later iterations 
    close $fh; 
} 

這將創建四個文件,file_1.txt等,以及它們的拷貝,copy_1.txt

請注意:強制檢查是否open工作。

+0

感謝您的幫助,我現在想這一個我的代碼做工精細 –

3

你不能寫,這不是打開用於寫入的文件句柄。您無法從不可讀取的文件句柄讀取數據。切勿忽略open的返回值。

# !/usr/bin/perl 
use warnings;        # Be warned about mistakes. 
use strict;        # Prohibit stupid things. 

for my $i (1 .. 4) {      # lexical variable, range 
    open my $FH1, '>', "/u/man/fr$i.txt" # 3 argument open, lexical filehandle, open for writing 
     or die "$i: $!";     # Checking the return value of open 

    print "Enter text for file $i: "; 
    my $txt = <STDIN>; 
    print {$FH1} $txt; 

    open my $FH2, '<', "/u/man/fr$i.txt" # Reopen for reading. 
     or die "$i: $!"; 
    open my $FH3, '>', "/u/man/result/fr$i.txt" or die "$i: $!"; 
    while (<$FH2>) { 
     print {$FH3} $_; 
    } 
    close $FH3; 
} 
+0

感謝我使用的建議,它有很大的幫助因爲我的文件沒有正確打開 –

0

我使用filehandler1打開的文件中寫入模式,然後使用我一樣filehandler1然後我打開destiantion filehandler2所以它是我工作的罰款,然後再次打開該文件中讀取模式。

0
system("cp myfile1.txt /somedir/myfile2.txt") 
`cp myfile1.txt /somedir/myfile2.txt`