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;

I want perl to print output within newlines in the file to which it is writing. How can I check if a line in the input file is null or not.

I would like the output to look like this (in ip.txt):

123.121.121.0
545.45.45.45 
..
..
etc
Keith Smiley
  • 61,481
  • 12
  • 97
  • 110
smart boy
  • 671
  • 4
  • 11
  • 24
  • 1
    Please indent your code. Why are you truncating the file `ip.txt` for every line you read? Please learn about `use strict;` and `use warnings;` and avoid bareword file handles; that's so early-90s style Perl — use `my $file = "data.txt"; open my $fh, '<', $file or die "Failed to open file $file for reading";` (also error checking the open operation). – Jonathan Leffler Jul 04 '13 at 17:33

1 Answers1

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 );
doubleDown
  • 8,048
  • 1
  • 32
  • 48
  • You should die on failing to open the input file, too, shouldn't you? – Jonathan Leffler Jul 04 '13 at 17:35
  • Its from `Best Practices`. Also seen [here](http://stackoverflow.com/questions/318789/whats-the-best-way-to-open-and-read-a-file-in-perl) –  Jul 04 '13 at 17:39
  • Okay, to make it more specific. `Best Practices`, Chapter 10. But he use `croak`. I prefer that way more than `die`, too. –  Jul 04 '13 at 17:45
  • You should `die` on closing a file. If it's was an input file, you will see any read errors. If it was an output file, closing first prints anything remaining in the buffer, then closes; and you should print an errors. – shawnhcorey Jul 04 '13 at 18:19
  • Croak is specifically for a package when you want to make sure that the caller gives the error and not the method. Otherwise, you can use die. Even better, use `autodie;` and then you don't need `die` or `croak`. – David W. Jul 04 '13 at 20:37