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

Passing a filehandle to a sub-routine

Status
Not open for further replies.

Loon

Programmer
May 24, 2000
100
GB
Just to check, I am doing this correctly?<br><br><FONT FACE=monospace>my $fh = open(INF, &quot;afile.txt&quot;) or die;<br><br>my output = &read_from_file(\*INF);<br><br>sub read_from_file()<br>{<br>&nbsp;&nbsp;&nbsp;&nbsp;while(&lt;$_[0]&gt;)<br>&nbsp;&nbsp;&nbsp;&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;etc......<br></font><br><br>Cheers<br>Loon<br><br>
 
Hi Loon,<br><br>The script below works, it prints itself. The only difference is that I've used $h=shift and &lt;$h&gt; instead of just &lt;$_[0]&gt; which I couldn't get to work....<br><br><br>#!/usr/bin/perl<br>&nbsp;<br>my $fh = open(INF, $0) or die;<br>&nbsp;<br>print &read_from_file(\*INF);<br>&nbsp;<br>sub read_from_file()<br>{<br>my $l;<br>my $h = shift;<br>&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while(&lt;$h&gt;) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$l = $l . $_;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$l;<br>} <p>Mike<br><a href=mailto:michael.j.lacey@ntlworld.com>michael.j.lacey@ntlworld.com</a><br><a href= Cargill's Corporate Web Site</a><br>
 
Why not just use the filename as the function parameter?<br><br>eg.<br><br>#!/usr/bin/perl<br>&nbsp;<br>print &read_from_file($filename);<br>&nbsp;<br>sub read_from_file()<br>{<br>&nbsp;&nbsp;my ($filename) = @_;<br>&nbsp;&nbsp;open(INF, $filename) or die;<br>&nbsp;&nbsp;@INF = &lt;INF&gt;;<br>&nbsp;&nbsp;close(INF);<br>&nbsp;&nbsp;return @INF;<br>}<br><br>Sincerely,<br><br>Tom Anderson<br>CEO, Order amid Chaos, Inc.<br><A HREF=" TARGET="_new">
 
Hi Tom,<br><br>Yep - passing a filename works fine - just that it's sometimes nice to pass a reference to an already open file.<br><br>For instance - working your way through an input file like this<br><br>while(&lt;F&gt;){<br>&nbsp;&nbsp;&nbsp;&nbsp;ProcessHeaders(\F);<br>&nbsp;&nbsp;&nbsp;&nbsp;ProcessDetailLines(\F);<br>&nbsp;&nbsp;&nbsp;&nbsp;ProcessFooterLines(\F);<br>}<br><br>this way you can work your way through an open file and make the logic of the way your script works a bit more transparent.<br><br>And &quot;Hi&quot; by the way - nice to see you on TT<br> <p>Mike<br><a href=mailto:michael.j.lacey@ntlworld.com>michael.j.lacey@ntlworld.com</a><br><a href= Cargill's Corporate Web Site</a><br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top