Perl 正确读取文件、处理输入并将输出写入第二个文件的最佳方法

Perl 正确读取文件、处理输入并将输出写入第二个文件的最佳方法,perl,Perl,将为data.txt中的每一行打开ip.txt的文件句柄。这太可怕了,会覆盖所有内容。您打开它是为了写(),而不是附加(>)。这里有一个更好的代码。请使用3参数open,不要将barewords用作文件句柄 123.121.121.0 545.45.45.45 .. .. etc #/usr/bin/perl 严格使用; 使用警告; my$file='data.txt' 我的$ip_文件='ip.txt'; 打开(my$FILE,'请缩进您的代码。为什么您要为您阅读的每一行截断文件ip.tx

将为data.txt中的每一行打开ip.txt的文件句柄。这太可怕了,会覆盖所有内容。您打开它是为了写(
),而不是附加(
>
)。这里有一个更好的代码。请使用3参数
open
,不要将barewords用作文件句柄

123.121.121.0
545.45.45.45 
..
..
etc
#/usr/bin/perl
严格使用;
使用警告;
my$file='data.txt'
我的$ip_文件='ip.txt';

打开(my$FILE,'请缩进您的代码。为什么您要为您阅读的每一行截断文件
ip.txt
?请了解
use strict;
use warnings;
并避免使用裸字文件句柄;这是90年代早期风格的Perl-使用
my$FILE=“data.txt”;打开我的$fh,'你也应该在无法打开输入文件时死去,不是吗?这是来自
最佳实践
。为了更具体,也可以这样看。
最佳实践
,第10章。但他使用
嘎嘎声
。我更喜欢这种方式,而不是
死亡
。你应该在关闭文件时死亡。
输入文件时,您将看到任何读取错误。如果是输出文件,关闭首先打印缓冲区中剩余的任何内容,然后关闭;您应该打印错误。当您希望确保调用方给出错误而不是方法时,Croak专门用于包。否则,您可以使用die。更好的是,使用
autodie;
然后你就不需要
die
croak
123.121.121.0
545.45.45.45 
..
..
etc
#!/usr/bin/perl

use strict;
use warnings;
my $file = 'data.txt'
my $ip_file = 'ip.txt';
open( my $FILE, '<',$file ) || die "Can't open $file for reading $!";
open( my $F, '>',$ip_file ) || die "Can't open $ip_file for writing $!";
while ( my $line = <$FILE> ) {

  my ( $ip, $me, $id ) = split( " ", $line );
  print "Ip: $ip\n";
  print $F "$ip \n";
  print "me: $me\n";
  print "ID: $id\n";
  print "---------\n";
}
close ($F);
close( $FILE );