Filehandles

G

Guenther Sohler

Hallo,

I am writing a small parser in perl, which should also be able to
include files.
if a include statement happens,
the prg shall put the current FH onto the stack and open a new file with
the same FH.

How can I do this as filehandles are special in perl ?
 
T

Tassilo v. Parseval

Also sprach Guenther Sohler:
I am writing a small parser in perl, which should also be able to
include files.
if a include statement happens,
the prg shall put the current FH onto the stack and open a new file with
the same FH.

How can I do this as filehandles are special in perl ?

Just pretend that they aren't special. Filehandles no longer need to be
barewords:

open my $fh, "<", $file or die "$file: $!";
push @stack, $fh;

...

# and then later
my $element = pop @stack;
if (ref($element) eq 'GLOB') { # is it a filehandle?
while (<$element>) { # then: read file
...
}
}

Note that your terminology is a bit sloppy: If it's a filehandle then
the underlying file has already been opened and you cannot really "open
a new file with the same FH".

Tassilo
 
A

Anno Siegel

Guenther Sohler said:
Hallo,

I am writing a small parser in perl, which should also be able to
include files.
if a include statement happens,
the prg shall put the current FH onto the stack and open a new file with
the same FH.

How can I do this as filehandles are special in perl ?

You use what is known as a lexical filehandle:

open my $fh, $file;

These are (slightly simplified) lexical variables that contain a reference
to an anonymous filehandle. The filehandle itself is still global.

Also search CPAN for the keyword "include". What comes up looks like
your problem has been dealt with before.

Anno
 
T

Tad McClellan

Guenther Sohler said:
put the current FH onto the stack
How can I do this as filehandles are special in perl ?


perldoc -q filehandle


How can I make a filehandle local to a subroutine? How do I
pass filehandles between subroutines? How do I make an array
of filehandles?
 
B

Brian McCauley

Tassilo said:
Note that your terminology is a bit sloppy: If it's a filehandle then
the underlying file has already been opened and you cannot really "open
a new file with the same FH".

Er, no. Perl filehandles (aka "IO thingys") can exist in a closed state
and a new file can be associated with an existinh file handle with open().
 
B

Brian McCauley

Brian said:

Ignore that.

I now realise you were drawing a destinction between "file handle" and
"IO handle". When a filehandle is closed it just becomes a closed IO
handle.
 

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,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top