Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have the following:

#! /usr/bin/perl
use Fcntl ':flock';
use strict;
...
    my (@list, $fh);
    open $fh, "<:encoding(utf8)", $file or die "$file: $!";
    flock $fh, LOCK_EX;
    use sigtrap 'handler' => sub {flock($fh, LOCK_UN);}, 'normal-signals'; # line 72

It runs but gives an error when I press ^C:

$ verify.pl
...
Can't use an undefined value as a symbol reference at ./verify.pl line 72.

The docs says it's OK

$ perldoc sigtrap
...
        use sigtrap 'handler' => \&my_handler, 'normal-signals';

I can't figure out what's wrong.

share|improve this question

I'm going to suggest that $fh is the undefined symbol reference. The use is run during the compilation phase (as if in a BEGIN {...} block), and, depending on where you think you're calling it, the $fh may never have been opened, or its scope may not be what you think.

Add some debugging to your handler to show, for example, the value of $fh and the refaddr of $fh. Also add to your open/flock code the same. I bet the refaddr isn't the same.

Since the sigtrap is registered globally, you may be best off with a global, e.g.:

my @handlers;
use sigtrap handler => sub { $_->() for grep defined, @handlers }, 'normal-signals';

{
  my ($fh, @list);
  open my $fh, ...
  flock $fh, LOCK_EX;
  my $handler = sub { flock $fh, LOCK_UN };

  @handlers = map { weaken $_ } grep defined, @handlers, $handler;
  # ... do stuff. When $handler goes out of scope, it'll go undef in @handlers
}
share|improve this answer
    
What is refaddr? perldoc.perl.org/search.html?q=refaddr – Chloe Jan 19 at 22:51
    
@Chloe Scalar::Util::refaddr – ThisSuitIsBlackNot Jan 19 at 23:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.