2012-10-05 10 views
13

文件考慮:寫在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寫的,但它似乎並沒有工作。我怎樣才能使它工作?

回答

25

變量僅在使用雙引號的字符串中插入"。如果您使用單引號'$將被解釋爲美元。

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

+6

您應該總是使用open-with-3文件句柄的open-my $ filehandle,'>>' ,$文件或死'可怕';' – dgw

+0

我有編譯問題與croak。使用die而不是 –