reading a text file in perl?

jnbill1204

New member
I am reading a text file in perl and trying to display the text but when I run the code below it doesn't create the new line. Can someone explain what I am doing wrong?


open (MYFILE, 'perlfile.txt');
while (<MYFILE>) {
chomp;
(my $u) = split("\t");
print "url: $u\n";

}
close (MYFILE);
Here is my full code:

use warnings;
use strict;
use Email::Find;
use LWP::Simple;
use HTML::LinkExtor;
use HTML::TokeParser;
use Data::Dumper;
use URI::URL;
use Text::CSV;
use DBI;


open (INPUT, "perlfile.txt") or die "Can't open data file: $!";
my $line;
my $counter = 1;
my @fields;
while (<INPUT>) {

@fields = split('/\t/', $_);
print @fields;

$counter++;
}

close INPUT;


my text file looks like this:

http://www.yahoo.comhttp://wwww.google.com bing.com

It all being read as one big string and not splitting.

the out put ishttp://www.yahoo.comhttp://wwww.google.com bing.com in one string.


I can't figure it out
 
1. You forgot "use strict;"
2. You forgot "use warnings;"
3. You forgot to check the return value of open()
4. You should not use the cryptic $_ defaults; you should use an explicit declared variable instead of $_
5. "my" should never appear inside parentheses; try "my ($u)"
6. The first argument to split() is supposed to be a regular expression, not a string. Try "split(/\t/)"
7. I don't know what "create the new line" means. SHOW US WHAT YOUR OUTPUT LOOKS LIKE and what you think it should look like
 
What is an example of your input?

My best guess is that the file is being read as one big string and so the while loop would execute just once or twice. Try adding a counter to see how many times the loop is being executed.

my $counter = 1;
open (MYFILE,'test.txt');
while (<MYFILE>) {
..... chomp;
..... (my $u) = split("\t");
..... print "url: $u\n";
..... $counter++;
}
close (MYFILE);

print "Counter: ". $counter;

Another test would be to create your own file manually with say 5 or 10 lines and see if it behaves as expected. If it does that your original file is to blame and is likely not formatted with new lines.
 
Back
Top