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

Hi,

I'm hoping this may be an easy question to someone. I'm currently stuck with a rather infuriating problem of attempting to open files whose names are the line by line contents of a previously read file. Running the current extract below returns

readline() on closed filehandle INQ_ET.

If I explicitly declare what the file names should be in advance (by uncommenting the foreach loop and commenting the first while loop, the script works.

Thanks
-----------------------------------------------------------
#!/usr/bin/perl -w open (HOSTLIST, hosts"); while ($host = <HOSTLIST>) { chomp ($host); #foreach $host ( 'hosta','hostb' ) { print "$host\n"; open (INQ_ET, "$host"); $, = ' '; # set output field separator $\ = "\n"; # set output record separator foreach (<INQ_ET>) { if (/\/dev/) { s/://g; ($Fld1,$Fld2,$Fld3,$Fld4,$Fld5,$Fld6) = split(' ', $_, 9999); printf ("'%s','%s','%s','%s','%s'\n", $Fld1, $Fld2, $Fld3, $Fld +6, $host); } } close (INQ_ET); }
Edited by castaway - added code tags .

Replies are listed 'Best First'.
Re: open and closing filehandles within a loop
by Zaxo (Archbishop) on Oct 28, 2003 at 06:15 UTC

    You've got most of the elements there, but you've commented out the loop. Its problem appears to be overuse of the $host variable, as well as some typos. Here's my take,

    #!/usr/bin/perl -w use strict; open HOSTLIST, "< hosts" or die $!; my @hosts = <HOSTLIST>; chomp @hosts; close HOSTLIST or die $!; for my $host (@hosts) { open INQ_ET, "< $host" or warn $! and next; for (<INQ_ET>) { # do stuff } close INQ_ET; }

    After Compline,
    Zaxo

      Zaxo,
      Superb! this worked. Thanks very much for taking the time to reply like this and thanks to everyone else who offered advice

      Paul
Re: open and closing filehandles within a loop
by pg (Canon) on Oct 28, 2003 at 06:14 UTC

    Most of the time you see this message, because you didn't actually open the file (common reasons could be: the file does not exist, there are garbage chars in filename etc.). It is always a good practice to check the return code of function calls. In this case, what you should do is:

    open(ABC, "<abc") || die "failed to open file\n";

    Or something similar (usually you don't want to die, but handle it and continue with the next file).