File Handle Issue

L

Louis

Hope somebody can tell me why this happens to filehandles...

I am playing with perl packages, and I had all functions in one file.
Now I want to split them into different files using package.

BEFORE: I have a function that opens a filehandle (FH1) and then calls
another function to print messages. This works good.

NOW: I put the calling function in another file. When it calls the print
function it uses &main::prtmess();, perl prints out errors: printf() Non
unopened filehandle FH1 at.....

ANd if I copy the prtmess() function in the same file as the calling
function, it works again.


My question is: I read somewhere that once you open a filehandle, perl
keeps it open until you close it. So why the different file scenario
doesn't seem to work?

Appreciate the help. Thanks.
 
J

Joe Smith

Louis said:
BEFORE: I have a function that opens a filehandle (FH1) and then calls
another function to print messages. This works good.

NOW: I put the calling function in another file.

In that case, you should store the file handle in a variable,
instead of using "FH1".
 
M

Michael Wehner

Louis said:
NOW: I put the calling function in another file. When it calls the print
function it uses &main::prtmess();, perl prints out errors: printf() Non
unopened filehandle FH1 at.....

Firstly, it's probably not a good idea to be splitting these functions
across packages. If they have such interrelated functionality, why split
them up at all? And certainly if you have to split them up, they
shouldn't both be operating on a global filehandle, nor will that
produce readable and maintainable code.

A better alternative would be to have one subroutine to open a
filehandle and read from it, and another subroutine to handle the
printing. And if you insist on operating directly on the filehandle, you
should be using a scalar to hold the filehandle--not a bareword--which
could then be passed to another function.
My question is: I read somewhere that once you open a filehandle, perl
keeps it open until you close it. So why the different file scenario
doesn't seem to work?

Read documentation on Perl's symbol tables. Until then, stick with
scalars as filehandles.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top