2011-03-22 93 views
0

我無法使用FILEHANDLE將文件寫入文件data.txt。這兩個文件都在同一個文件夾中,所以這不是問題。自從我開始使用Perl之後,我注意到要運行腳本,我必須使用完整路徑:c:\ programs \ scriptname.pl,並且也使用相同的方法來輸入文件。我認爲這可能是問題,並試圖在下面的語法,但也沒有工作...文件句柄 - 不會寫入文件

open(WRITE, ">c:\programs\data.txt") || die "Unable to open file data.txt: $!"; 

這是我的腳本。我已經檢查了語法,直到它讓我發瘋,並且看不到問題。任何幫助將不勝感激!。我也百思不得其解,爲什麼芯片功能還沒有踢。

#!c:\strawberry\perl\bin\perl.exe 

#strict 
#diagnostics 
#warnings 

#obtain info in variables to be written to data.txt 
print("What is your name?"); 
$name = <STDIN>; 
print("How old are you?"); 
$age = <STDIN>; 
print("What is your email address?"); 
$email = <STDIN>; 

#data.txt is in the same file as this file. 
open(WRITE, ">data.txt") || die "Unable to open file data.txt: $!"; 

#print information to data.txt 
print WRITE "Hi, $name, you are \s $age and your email is \s $email"; 

#close the connection 
close(WRITE); 

我如何解決這個問題迎刃而解

我有c:驅動器上安裝了草莓Perl perl.exe,通過使用安裝程序和安裝程序以及c上的文件夾與我的腳本,這意味着我不能紅/寫入文件(定向或使用函數,即開放函數),我總是必須使用完整路徑來啓動腳本。我解決了這個問題,建議將解釋器安裝在原來的位置,並將腳本文件移動到桌面(將OS命令留在腳本的第一行,因爲解釋器仍處於最初的相同位置)。現在我只需點擊一下鼠標就可以運行這些腳本,並且可以通過讀取/寫入和附加到CMD提示符的文件並輕鬆使用Perl函數。

+1

錯誤消息說什麼? – Mat 2011-03-22 18:04:03

+0

它什麼也沒說。沒有一個 - 腳本運行,詢問3個問題,然後停下來。 – 2011-03-22 18:06:39

+1

嘗試'打印寫「你好,$名稱,你是\的$年齡和你的電子郵件是\的$電子郵件」或死「無法寫:$!」''' – ysth 2011-03-22 18:20:11

回答

1

您必須使用「/」,以確保可移植性,所以:open(WRITE, ">c:/programs/data.txt") 注:我認爲c:/programs文件夾存在

+0

是的,這兩個文件都在同一個文件夾(我知道這是一個問題,否則)。非常感謝,儘管這仍然行不通!我也感到困惑,爲什麼die功能沒有被踢入。 – 2011-03-22 18:12:12

+0

我認爲以'c:'開頭的文件名會自動阻止它的移植。你應該說要用'/'或'\\'來使它正常工作。如果你想討論可移植性,你應該討論使用[File :: Spec](http://perldoc.perl.org/File/Spec.html)或[File :: Spec :: Functions](http:// perldoc.perl.org/File/Spec/Functions.html)以及[Cwd](http://perldoc.perl.org/Cwd.html)和[FindBin](http://perldoc.perl.org/ FindBin.html) – 2011-03-22 18:25:39

+0

不,也沒有補救。謝謝。無論如何非常讚賞。 – 2011-03-24 14:31:03

1

你可能想嘗試FindBin

use strict; 
use warnings; 
use autodie; # open will now die on failure 

use FindBin; 
use File::Spec::Functions 'catfile'; 
my $filename = catfile $FindBin::Bin, 'data.txt'; 

#obtain info in variables to be written to data.txt 
print("What is your name?"); my $name = <STDIN>; 
print("How old are you?"); my $age = <STDIN>; 
print("What is your email address?"); my $email = <STDIN>; 

{ 
    open(my $fh, '>', $filename); 
    print {$fh} "Hi, $name, you are $age, and your email is $email\n"; 
    close $fh; 
} 
+0

謝謝布拉德,我會盡力的! – 2011-03-22 18:21:14

1

如果當您嘗試打印到data.txt中有一個訪問問題,你可以該行更改爲:

print WRITE "Hi, $name, you are \s $age and your email is \s $email" || die $!; 

以獲取更多信息。只讀文件將導致此錯誤消息:

Unable to open file data.txt: Permission denied at perl.pl line 12, <STDIN> line 3. 
+0

謝謝。非常感激。 – 2011-03-24 14:30:41

2

反斜槓在雙引號字符串中有特殊含義。嘗試逃避反斜槓。

open(WRITE, ">c:\\programs\\data.txt") || die ...; 

或者,因爲您不是插值變量,請切換到單引號。

open(WRITE, '>c:\programs\data.txt') || die ...; 

這也是值得使用的三參數版本的開放和詞法文件句柄。

open(my $write_fh, '>', 'c:\programs\data.txt') || die ...; 
+0

謝謝davorg !. – 2011-03-27 18:51:37