16

考虑:

#!/usr/local/bin/perl
$files = "C:\\Users\\A\\workspace\\CCoverage\\backup.txt";
unlink ($files);
open (OUTFILE, '>>$files');
print OUTFILE "Something\n";
close (OUTFILE);

上面是我用Perl写的一个简单的子程序,但是好像不行。我怎样才能让它工作?

4

1 回答 1

29

变量仅在使用双引号的字符串中插入"。如果您使用单引号'$则将被解释为美元。

尝试使用">>$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";
于 2012-10-05T04:30:51.433 回答