简体   繁体   English

在Perl中使用文件句柄将STDIN写入文件

[英]Writing STDIN to a file using filehandle in perl

I have just started learning perl and I was going through filehandle. 我刚刚开始学习perl,正在查看文件句柄。

  1. I want to write my STDIN to a file. 我想将我的STDIN写入文件。 How do I do it using filehandle ? 我该如何使用filehandle呢?
  2. Also is it possible to do the same, without using FH ? 也可以不使用FH进行相同的操作吗?

I tried the below, but never worked: 我尝试了以下方法,但从未成功:

#!/usr/bin/perl

$file = 'File.txt';

open ($fh, '>', $file) or die "Error :$!";

print "Enter blank line to end\n";

while (<STDIN>) {

    last if /^$/;
    print "FH: $fh \n";
    print "dollar: $_ \n";
}

close $fh;* 

The below works, but I don't understand why. 下面的作品,但我不明白为什么。

#!/usr/bin/perl

open(my $fh, '>', 'report.txt');

foreach my $line ( <STDIN> ) {

    chomp( $line );

    print $fh "$line\n";
}

close $fh;


print "done\n"; 

You have opened the filehandle $fh for writing to your file. 您已打开文件句柄$fh来写入文件。 Your second example prints data to this filehandle, so it works: 您的第二个示例将数据打印到此文件句柄,因此可以正常工作:

print $fh "$line\n";

But your first example doesn't print to $fh , so the output goes to STDOUT . 但是您的第一个示例未打印到$fh ,因此输出到STDOUT

print "FH: $fh \n";
print "dollar: $_ \n";

In order for your first example to work, you need to print to the correct filehandle. 为了使第一个示例生效,您需要打印到正确的文件句柄。

print $fh "FH: $fh \n";
print $fh "dollar: $_ \n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM