Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read Files

Status
Not open for further replies.

blakee

Programmer
Jan 18, 2005
22
Whats wrong with this code? I'm new at this stuff and I kept reading tutorials and it dosen't seem anything is wrong with it except it dosen't print any text in the foreach loop.. Oh and I'm also on a Windows OS..

#!usr/local/bin/perl

use strict;

$data_file="test.txt";

open(TEST, $data_file) || die("Could not open $data_file");
@raw_data=<TEST>;
close(TEST);

foreach $test (@raw_data)
{
print "$test";
}
 
change
Code:
$data_file="test.txt";
to
Code:
$data_file="[b]<[/b]test.txt";
and make sure there's something in test.txt before starting, but try
Code:
print "[$test]\n";
it'll make a difference

HTH
--Paul

cigless ...
 
You want to read & print the lines in "test.txt"?
Code:
ruby  -pe "" test.txt
Code:
awk 1 test.txt
 
Adding "<" before the file name shouldn't make a difference, as the default is to open files for input unless otherwise specified. (I agree that it's a good idea to use it, though I confess I often don't.)

blakee, I suspect the code you've posted here is not the actual code that you're running. You say "it dosen't seem anything is wrong with it except it dosen't print any text in the foreach loop," yet you have use strict in your script, but aren't declaring your variables with my. strict requires that you declare your variables this way, and will certainly let you know that something is wrong if you try to run without doing this.

Read up on strict and my:
perldoc strict
perldoc -f my

and declare your variables with my.

If you still aren't getting any output after that, check to see if there's actually anything in your input file. Is the file empty?

 
Personally for this sort of thing I would use File::Slurp, which reads in files quickly, efficiently and securely.

Code:
#!usr/local/bin/perl -w
use strict;

use File::Slurp;

my $data_file="test.txt";

my @raw_data=read_file($data_file);
foreach my $test (@raw_data) {
   print "$test";
}

Barbie
Leader of Birmingham Perl Mongers
 
Also, if you are on *nix, your shebang line looks wrong, needs a leading '/' before the usr/...
 
This is close to what you did and easy to understand!


use strict;

my $file = "myfile.some_extension";

open(FILE, $file);
while (<FILE>)
{
print $_;
}
close(FILE);

so simple
 
I got it working, I guess when I have a .pl on my desktop I need the .txt in c:\documents and settings\administrator\ directory.. after i put the .txt in that folder then it read it.. thanks
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top