在perl中将新行写入文件

时间:2013-04-24 22:51:52

标签: perl

我正在学习perl并编写脚本以将脚本目录树中的所有内容输出到文件中。问题出在文本文件中,即使我包含“\ n”,整个输出也在一行上。我将保存代码打印到控制台,我在那里得到了所需的结果,每行一个条目。

#!/usr/bin/perl -w

use Cwd;
use File::Find;
use strict;

my $file = "temp.txt";
my $dir  = getcwd;

unless ( open FILE, '>>' . $file ) {
    die "\nUnable to create $file\n";
}

find( \&print_type, $dir );

sub print_type {
    if (-f) {
        print FILE "File: " . "$_\n";
        print "File: " . "$_\n";
    }
    if (-d) {
        print FILE "Directory: " . $_ . "\n";
        print "Directory: " . $_ . "\n";
    }
}
close FILE;

我也尝试在“目录:”之前放置\ n,但这也不起作用。

2 个答案:

答案 0 :(得分:2)

原来代码工作正常,但是我使用Windows记事本来读取我的输出文件并且它无法识别“\ n”,我只需要在几乎任何其他文本编辑器中打开它以查看( notepad ++,wordpad,emacs)。

如果我没有使用Cygwin,可能是记事本可以工作。

答案 1 :(得分:1)

以APPEND模式或WRITE模式打开文件,并使用打开的文件描述符进行写入并将数据附加到文件中,使用perl中的PRINT stantment。 在Linux中只考虑“\ n”,而不是WINDOW用户,所以Linux用户 在名为NEWLINE“\ n”;

的每一行末尾添加一个额外的字符
相关问题