考虑以下情况:
#!/usr/local/bin/perl
$files = "C:\\Users\\A\\workspace\\CCoverage\\backup.txt";
unlink ($files);
open (OUTFILE, '>>$files');
print OUTFILE "Something\n";
close (OUTFILE);
这是我用Perl编写的一个简单子例程,但似乎它不能工作。我该如何使它工作?
考虑以下情况:
#!/usr/local/bin/perl
$files = "C:\\Users\\A\\workspace\\CCoverage\\backup.txt";
unlink ($files);
open (OUTFILE, '>>$files');
print OUTFILE "Something\n";
close (OUTFILE);
这是我用Perl编写的一个简单子例程,但似乎它不能工作。我该如何使它工作?
只有在双引号"
的字符串中变量才会被插值。如果使用单引号'
,则$
将被解释为一个美元符号。
尝试使用">>$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";
open my $filehandle , '>>' , $file or die 'Horribly';
。 - dgw