在Perl中写入文件

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编写的一个简单子例程,但似乎它不能工作。我该如何使它工作?

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";

3
您可以安装 Perl::Critic 工具,它可以检查 Perl 代码中常见的问题和错误,非常实用。 - Matteo
7
你应该始终使用带有词法文件句柄的三参数版本 open my $filehandle , '>>' , $file or die 'Horribly'; - dgw
我在使用croak时遇到了编译问题。请改用die。 - Sam B
@Sam B:哪些问题?你有包含"use Carp;"吗? - Matteo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接