home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / perl / 7502 < prev    next >
Encoding:
Text File  |  1992-12-18  |  1.3 KB  |  41 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!ftpbox!mothost!merlin.dev.cdx.mot.com!fendahl.dev.cdx.mot.com!mcook
  3. From: mcook@fendahl.dev.cdx.mot.com (Michael Cook)
  4. Subject: Re: array of file descriptors
  5. Message-ID: <mcook.724624901@fendahl.dev.cdx.mot.com>
  6. Sender: news@merlin.dev.cdx.mot.com (USENET News System)
  7. Nntp-Posting-Host: fendahl.dev.cdx.mot.com
  8. Organization: Motorola Codex, Canton, Massachusetts
  9. References: <1992Dec17.171242.22639@ans.net>
  10. Date: Thu, 17 Dec 1992 20:41:41 GMT
  11. Lines: 28
  12.  
  13. fuat@news.ans.net (Fuat C. Baran) writes:
  14.  
  15. >Is there a way to store file descriptors (from an open()) in an array?
  16. >I would like to open a set of files, store the open file descriptors
  17. >in an associative array keyed by filename and be able to multiplex
  18. >output to one of the files in a loop where for each line of output I'm
  19. >given a filename.  I'd like to check if $filehandles{$filename} is
  20. >defined and if not first open the file.
  21.  
  22. You can generate your own file handle symbols:
  23.  
  24.   $gensym = "fh0000";
  25.   foreach $file (@file)
  26.   {
  27.      open(++$gensym, "<$file") || die "oops: $file, $!";
  28.      $fh{$file} = $gensym;
  29.   }
  30.  
  31. The trick is using the file handle with the <> operator:
  32.  
  33.   $_ = <$fh{$file}>;    # doesn't seem to work
  34.  
  35.   $tmp = $fh{$file};    # need an extra variable
  36.   $_ = <$tmp>;
  37.  
  38. See also cacheout.pl.
  39.  
  40. Michael.
  41.