0
#!/usr/bin/perl

 open (FILE, 'data.txt');
 while (<FILE>) {

 ($ip,$me,$id) = split(" ");

 print "Ip: $ip\n";

 open(F,'>ip.txt') || die $!;

  print F  "$ip \n" ;

close(F);

 print "me: $me\n";
  print "ID: $id\n";
 print "---------\n";
 }
 close (FILE);
 exit;

我希望 perlprint 在它正在写入的文件的换行符内输出。如何检查输入文件中的一行是否为空。

我希望输出看起来像这样(in ip.txt):

123.121.121.0
545.45.45.45 
..
..
etc
4

1 回答 1

2

Your filehandle of the ip.txt is opened for every row in your data.txt. That's horrible and overwrites all content. You open it for writing (>), not appending (>>). Here is a better code. Please use the 3-argument open and don't use barewords as filehandles.

#!/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 );
于 2013-07-04T17:34:32.197 回答