我有一个变量包含在我需要写入文件的变量中。我的脚本需要创建文件然后写入它。
这是我目前的剧本:
my $file_location = '/network/$custom_directory/$custom_filename';
open(my $file ">", $file_location) or die $!;
print $file "$variable_data";
close $file;
我感觉我的脚本在实际的文件创建上被挂起,而不是变量编写过程。 我运行脚本时遇到的错误是:'我没有这样的文件或目录'在我尝试打开文件的行。
答案 0 :(得分:9)
您的程序中存在语法错误。 open
的所有三个参数必须用逗号分隔。
open my $file, '>', $file_location or die $!;
单引号不插入,与双引号不同,因此您可能需要在文件路径中使用它们:
my $file_location = "/network/$custom_directory/$custom_filename";
顺便说一句:将单个变量包含在双引号服务器中对字符串内容没有用处。你可以等效地
print $file $variable_data;
答案 1 :(得分:4)
你没有说出你的错误是什么。
这给了你这样的东西,强制性的序言:
#!/usr/bin/perl
use strict;
use warnings;
my $custom_directory = "something old";
my $custom_filename = "something new";
my $data = "something borrowed";
my $path = "/network/$custom_directory/$custom_filename";
open(my $handle, ">", $path) || die "can't open $path: $!";
binmode($handle); # for raw; else set the encoding
print $handle "$data\n";
close($handle) || die "can't close $path: $!";
答案 2 :(得分:3)
两件事:首先文件位置是单引号,因此$
变量不会被插值。其次,您在open
的调用中缺少逗号。代码应为:
my $file_location = "/network/$custom_directory/$custom_filename";
open(my $file, ">", $file_location) or die $!;
答案 3 :(得分:3)
首先,
use strict;
use warnings;
可能有所帮助。其次,变量插值需要双引号字符串:
my $file_location = "/network/$custom_directory/$custom_filename";
第三,您可能需要在打印声明中使用\ n:
print $file "$variable_data\n";
最后,你的公开声明应该是:
open my $file, ">", $file_location or die $!;