solitaryrpr has asked for the wisdom of the Perl Monks concerning the following question:

Greetings fellow monks,

I need to parse a file that can include other files (which can include other files, etc). I think the easiest way to handle this would be recursion but I'm not sure how well perl handles opening a filehandle with the same reference. To clarify:

sub get_hosts { my $file = shift; open (HOSTS, <$file) or die("I can't open $file"); while (<HOSTS>) { if ( /^include (.*)$/ ) get_hosts($1); &parse_line; } close HOSTS; }

Can perl handle this gracefully? If not, what are my options? I can try it and see but thought I'd ask.

-sol

Replies are listed 'Best First'.
Re: recursive file open
by Fletch (Bishop) on May 05, 2007 at 03:28 UTC

    Not that way, no. Filehandles (of that form) are global and when you reopen one the previous file is closed. Either localize it with, erm, local or use a lexical handle (given a new enough Perl).

    open( my $hosts_fh, "<", $file ) or die "probelm opening '$file': $!\n +";
Re: recursive file open
by merlyn (Sage) on May 05, 2007 at 05:57 UTC
      sweet...I probably even have the SysAdmin mag it was in. Thanks.