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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing file handles to subroutines 2

Status
Not open for further replies.

fortytwo

Technical User
Apr 18, 2000
206
GB
Hi,

I have a program that has six open file handles that I need to make the same regex pattern match on. So to avoid writing the pattern match six times I have a function that does the pattern match, but how do you pass a file handle to a subroutine? Something that would look like this:
[tt]
sub search {
while (<some passed file handle>) {
#do something
}
return (&quot;something&quot;);
}

$variable1 = &search(<filehandleA>);
$variable2 = &search(<filehandleB>);
$variable3 = &search(<filehandleC>);
[/tt]

any ideas?


fortytwo
will@hellacool.co.uk
 
I found this in &quot;Perl Cookbook&quot; by Tom Christiansen and Nathan Torkington - p. 255, recipe 7.16:

$variable = *FILEHANDLE; # save in variable
subroutine(*FILEHANDLE); # or pass directly

sub subroutine {
my $fh = shift;
print $fh &quot;Hello, filehandle!\n&quot;;
}

There's more, but this should get you going. I highly recommend the &quot;Perl Cookbook&quot; - I give it 5 out of 5 stars.

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
There is also a lot of information in the perl docs about passing filehandles.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
I got the perl cookbook. Thanks for the help. I have not got it working yet but I have something to work on for the time being :)

fortytwo
will@hellacool.co.uk
 
Hi, I think I am getting there but I have come accross a problem. I don't seem able to get any useful information out of the file handle that I passed to the sub:

[tt]
sub search
{
my $fh = shift;
while (<$fh>)
{
print;
}
return (&quot;End of the sub&quot;);
}

open (HANDLE, &quot;multi_line_file.txt&quot;) || die &quot;Failed to open file : $!\n&quot;;

$result = search(*HANDLE);
[/tt]

if I print $fh; inside the sub I get:

[tt]*main::HANDLE[/tt]

but I don't seem to be able to get it into the while loop, it gets to return (&quot;End of the sub&quot;); without having been in the while loop. Any ideas?

fortytwo
will@hellacool.co.uk
 
When you're passing the filehandle, pass the glob as a reference, so it's actually:
Code:
$result = search(\*HANDLE);
You'll still access it as $fh in the subroutine. That should do it.

brendanc@icehouse.net
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top