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!

Quick question about filehandles 1

Status
Not open for further replies.

johndoe3344

Programmer
Jul 5, 2007
13
US
The segment of code in question is:

open (INPUT, "input.txt") or die "Could not open input file.\n";

for my $var (<INPUT>) {
open (VAR, $var) or die "Failed. \n";
subroutine();
}

Let's say input.txt consists of the lines:
file_name_1.txt
file_name_2.txt
file_name_3.txt

What I want the script to do is open each of these files, and invoke a certain subroutine with each one. Would that work?
 
Yeah it would. You'd want to chomp each line you read in, though.

Code:
foreach my $var (<INPUT>) {
   chomp $var;
   open (VAR, $var) or die "Failed.\n";
}

Chomp gets rid of the end-of-line chars... ie if your text file is:

Code:
file_name_1.txt
file_name_2.txt
file_name_3.txt

The array of lines in it would be...

Code:
(
"file_name_1.txt\n",
"file_name_2.txt\n",
"file_name_3.txt",
);

-------------
Cuvou.com | My personal homepage
Project Fearless | My web blog
 

Code:
my $input = 'input.txt';
open(INPUT, $input) or die "Can't open $input: $!";

for my $filename (<INPUT>) {
	chomp $filename;
	open my $fh, '<', $filename or die "Can't open $filename: $!";
	subroutine($fh);
}

close(INPUT);

sub subroutine {
	my $fh = shift;
	while (<$fh>) {
		print "Found $_";
	}
}

Or better still, just let the subroutine handle the file operations.

- Miller
 
not sure how kosher it is to use a for/foreach loop on a filehandle. It may not check for eof properly?

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Actually you're right. I noticed that after posting, but obviously there's no edit ability.

- M
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top