變量僅在使用雙引號的字符串中插入"
。如果您使用單引號'
$
將被解釋爲美元。
與">>$files"
代替'>>$files'
嘗試始終使用
use strict;
use warnings;
這將有助於讓更多的警告。
在任何情況下也聲明變量
my $files = "...";
您還應該檢查的open
返回值:
open OUTFILE, ">>$files"
or die "Error opening $files: $!";
編輯:作爲建議的意見,一個版本的三個參數開放和一些其他可能的改進
#!/usr/bin/perl
use strict;
use warnings;
# warn user (from perspective of caller)
use Carp;
# use nice English (or awk) names for ugly punctuation variables
use English qw(-no_match_vars);
# declare variables
my $files = 'example.txt';
# check if the file exists
if (-f $files) {
unlink $files
or croak "Cannot delete $files: $!";
}
# use a variable for the file handle
my $OUTFILE;
# use the three arguments version of open
# and check for errors
open $OUTFILE, '>>', $files
or croak "Cannot open $files: $OS_ERROR";
# you can check for errors (e.g., if after opening the disk gets full)
print { $OUTFILE } "Something\n"
or croak "Cannot write to $files: $OS_ERROR";
# check for errors
close $OUTFILE
or croak "Cannot close $files: $OS_ERROR";
您還可以安裝Perl :: Critic一個有用的工具來檢查Perl代碼中的常見問題和錯誤 – Matteo
您應該總是使用open-with-3文件句柄的open-my $ filehandle,'>>' ,$文件或死'可怕';' – dgw
我有編譯問題與croak。使用die而不是 –