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

Hello!

Here comes the code:

use vars qw($LF); sub new { my $proto = shift; my $class = ref($proto) || $proto; open(FH, ">".LOCK_FILE) or die "ERROR: cannot open lock file: +".LOCK_FILE.": $!\n"; my $this = { LF => \*FH }; bless($this, $class); return $this; } .... # # code_lock() # Lock a section of code. # sub code_lock { my $this = attr shift; my $ret = flock $LF, LOCK_EX; return scalar $ret; }

This doesn't work because $FL appears to be undefined in code_lock(). If I change flock() call to the following:

flock $this->{'FL'}, LOCK_EX;
this works just fine! I am really wondering what is the problem here.

Thanks!

Replies are listed 'Best First'.
Re: a problem with a filehandle reference
by Rhandom (Curate) on Apr 19, 2001 at 23:39 UTC
    If you would like to make life more simple, you should use either IO::File or Filehandle or Symbol::gensym, as in the following.
    use IO::File (); # assuming LOCK_FILE is a constant with the filename my $fh = IO::File->new( LOCK_FILE, 'w' ); # now you can pass $fh directly to your sub # as in code_lock( $fh ); # sub code_lock { my $fh = shift(); }
    You could also create the same sort of thing with Filehandle or with the following code.
    use Symbol(); my $fh = Symbol::gensym(); open($fh,">".LOCK_FILE); # pass it as in the above
      Thanks! This should simplify the things. I am just really wondering why the approach doesn't work with filehandles. Is there something wrong with attr or am I doing stupid things? A.
        Without experimenting, you may need to do things like
        local *FH = \$this->{FL}; flock FH, LOCK_EX;
        or
        flock { $this->{FL} }, LOCK_EX;
        You have the same types of problems when trying to print on a handle stored in a hash.
Re: a problem with a filehandle reference
by suaveant (Parson) on Apr 19, 2001 at 23:06 UTC
    You never assign anything to $LF (and in your example you keep switching LF and FL)
                    - Ant
      Sorry, in the example it should be read as 'LF' and $LF. Actually, I believe I do assign.
      my $this = attr shift;
      should create localized $LF.
        I am not familiar with attr... and I can't find it in perldoc -f or the camel book... what does it do?
                        - Ant