写入Perl中的文件

Daa*_*ish 15 perl file-handling

考虑:

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

以上是我在Perl中编写的一个简单的子例程,但它似乎不起作用.我怎样才能使它工作?

Mat*_*teo 27

变量仅使用双引号在字符串中进行插值".如果使用单引号',$则将被解释为美元.

尝试">>$files"而不是'>>$files'

一直用

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

它将有助于获得更多警告.

在任何情况下也声明变量

my $files = "...";
Run Code Online (Sandbox Code Playgroud)

您还应该检查返回值open:

open OUTFILE, ">>$files"
  or die "Error opening $files: $!";
Run Code Online (Sandbox Code Playgroud)

编辑:正如评论中所建议的那样,打开三个参数的版本以及其他一些可能的改进

#!/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";
Run Code Online (Sandbox Code Playgroud)

  • 你应该总是使用lexical文件句柄打开的三参数版本`打开我的$ filehandle,'>>',$ file或die'Harribly';` (7认同)
  • 您还可以安装Perl :: Critic,这是一个有用的工具,可以检查Perl代码中的常见问题和错误 (3认同)