时间:2017-10-01 21:14:34

标签: perl io filehandle

我是Perl的新手(刚看过一个Youtube视频)。我想创建一个脚本,将需要两个.csv文件并将它们附加在一起,并创建一个新的.csv文件。我不希望更改要附加的两个.csv文件。我还想让这个脚本将用户输入作为要合并的文件(现在两个附加的.csv文件位于同一目录中)。

我一直得到的错误是:print()在关闭的文件句柄OUT第1行(#2)(W关闭)你正在打印的文件在此之前的某个时间关闭。检查控制流程

但我从未使用过close命令,所以我的文件句柄是如何关闭的?

use strict;
use warnings;
use diagnostics;
use feature 'say';
use feature "switch";
use v5.22;

# Ask for Base File
say "What is the base file you want to use?";
my $base_file = <STDIN>;
chomp $base_file;
open (BASE, '<', $base_file) or die "Couldn't find the base file you are entered: $base_file ";

# Ask for Append File
say "What is the file you want to append to the base file?";
my $append_file = <STDIN>;
chomp $append_file;
open (APPEND, '<', $append_file) or die "Couldn't find the append file you are entered: $append_file ";

# Create new File with new name
say "What is the name of the new file you want to create?";
my $new_file = <STDIN>;
open (OUT, '>>', $new_file);
chomp $new_file;
while(my $base_line = <BASE>) {
        chomp $base_line;
        print OUT $base_line;
}

1 个答案:

答案 0 :(得分:4)

你真的应该检查对open的来电是否成功。

open(OUT, '>>', $new_file)
   or die("Can't append to \"$new_file\": $!\n");

我打赌你会发现open失败了,我打赌你会发现它是因为你指定的文件不存在,我敢打赌您会发现$new_file包含不应该提供的换行符。

修复方法是将以下行移至open

之前
chomp $new_file;

顺便说一下,你不应该使用全局变量。将OUT替换为my $OUTBASEAPPEND相同。