On Wednesday 22 April 2009 16:30:34 Berler Chanan wrote:
> Hi All,
>
> Please take a look on this:
> I am trying to open a dictionary file, and read the lines, when I found a
> INCLUDE line, I need to open that file and read it too..
> The idea to create a concatenated and long file with all the include
> statements.
>
> Problem: when doing the first open it works, and then it encounter with the
> INCLUDE statement, and goes into recursion
> In the recursion I need to open the new file again, but looks like DICT is
> shared, and those it is closing the first file opened
>
> Anyone has an idea how to bypass this ?
The DICT is indeed shared because it's a typeglob.
Yes. You have several options:
1. Use lexical file-handles:
{{{
open my $dict_fh, "<", $dict_filename;
.
.
.
while (my $line = <$dict_fh>)
{
}
.
.
.
close($dict_fh);
}}}
This is always a good idea unless you need compatibility with really old
perl's. If you do, you may wish to take a look at the IO::File module.
2. In addition to (not instead of) #1 , you can read all the lines from the
file (a.k.a: "slurping"), then close the file-handle, and iterate over the
lines using foreach. Using this you will keep the number of open file-handles
to a minimum (but naturally consume more memory).
Regards,
Shlomi Fish
> Thanks
> Chanan
>
> sub _create_dictionary_
> {
> my ($dict_file, $depth) = @_;
> #our $buffer;
>
> if ($depth < 0)
> {
> # do not handle more than 5 nested INCLUDEs
> return;
> }
>
> open DICT, $dict_file or die "Error: can't open $dict_file for
> reading\n";
> while (my $line = <DICT>)
> {
> chomp($line);
>
> #$INCLUDE dictionary.compat
> if ($line =~ /^\$INCLUDE/)
> {
> # handle include statment
> my ($filename) = $line =~ /INCLUDE +(.*)/;
> _create_dictionary_("dict/$filename", $depth - 1);
> }
> $buffer .= "$line\n";
> }
> close DICT or die "Error: can't close $dict_file after reading\n";
> }
>
> _______________________________________________
> Perl mailing list
> [email protected]
> http://mail.perl.org.il/mailman/listinfo/perl
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Parody on "The Fountainhead" - http://xrl.us/bjria
God gave us two eyes and ten fingers so we will type five times as much as we
read.
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl