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

Hello, I want to open a file with a unique filehandle everytime it needs to be opened. Will the following work? => ----------------------
$seed = (time() ^($$ + ($$ <<15))); $fh = "FH_TEST".$seed; open (local $fh, "test.out"); while (<$fh>) { .............. .............. } close $fh;
---------------------- Background: The above code is in a perl module whose multiple instances are running in parallel through LSF. So each call of the module should generate a unique file handle with which to open the same file in read mode.

20080820 Janitored by Corion: Added formatting, code tags, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: Generate unique file handles
by moritz (Cardinal) on Aug 20, 2008 at 07:17 UTC
    Why not simply use a lexical variable as the file handle?
    open my $fh, '<', 'test.out' or die "Can't open test.out: $!";

    I don't think your approach works - did you try it?

      I have not yet tried it. Following is the issue faced with a fixed file handle name => Since the perl module is called in parallel through LSF, suppose one process finishes reading the file and closes the filehandle while another process is still reading the file, this file handle also gets closed and it never reads the file completely. Thats why I wanted to have unique file handle names. Can I try $fh_$$ so that it generates a unique file handle with process id?
        If LSF starts a new process for each job (and only in this case $$ will actually help you) it's not an issue at all, because perl variables aren't shared across processes. In this case you can even use bare word file handles, although I don't recommend them.

        Even if it uses perl threads, there's no need to worry because variables aren't shared by default.

        (As a side node when you think of a variable variable name, use a hash instead. So instead of the non-working $fh_$$ you'd use my %handles; $handles{$$} = ... instead. But as said above, no need here).

Re: Generate unique file handles
by Anonymous Monk on Aug 20, 2008 at 07:15 UTC
    use Symbol; $sym = gensym; open($sym, "filename"); $_ = <$sym>;
Re: Generate unique file handles
by bruno (Friar) on Aug 20, 2008 at 19:13 UTC
Re: Generate unique file handles
by ikegami (Patriarch) on Aug 21, 2008 at 20:06 UTC

    local $fh erases the content of $fh. And even if it didn't, open doesn't takea variable name for its first argument (just a variable).

    You can simply use

    open(my $fh, '<', 'test.out')

    Open returns a new anonymous file handle in $fh every time.