文件句柄 - 不会写入文件
我无法使用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函数。
您必须使用“/”,以确保可移植性,所以:open(WRITE, ">c:/programs/data.txt")
注:我认为c:/programs
文件夹存在
是的,这两个文件都在同一个文件夹(我知道这是一个问题,否则)。非常感谢,尽管这仍然行不通!我也感到困惑,为什么die功能没有被踢入。 – 2011-03-22 18:12:12
我认为以'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
不,也没有补救。谢谢。无论如何非常赞赏。 – 2011-03-24 14:31:03
你可能想尝试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;
}
谢谢布拉德,我会尽力的! – 2011-03-22 18:21:14
如果当您尝试打印到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.
谢谢。非常感激。 – 2011-03-24 14:30:41
反斜杠在双引号字符串中有特殊含义。尝试逃避反斜杠。
open(WRITE, ">c:\\programs\\data.txt") || die ...;
或者,因为您不是插值变量,请切换到单引号。
open(WRITE, '>c:\programs\data.txt') || die ...;
这也是值得使用的三参数版本的开放和词法文件句柄。
open(my $write_fh, '>', 'c:\programs\data.txt') || die ...;
谢谢davorg !. – 2011-03-27 18:51:37
错误消息说什么? – Mat 2011-03-22 18:04:03
它什么也没说。没有一个 - 脚本运行,询问3个问题,然后停下来。 – 2011-03-22 18:06:39
尝试'打印写“你好,$名称,你是\的$年龄和你的电子邮件是\的$电子邮件”或死“无法写:$!”''' – ysth 2011-03-22 18:20:11