http://www.perlmonks.org?node_id=1045543


in reply to Passing arguments to a function reference

SIG{"ALRM"}=\&Timeout($error);

I have a single subroutine that handled the timeouts, but I want it to get a different arguments based on the bit of code where the timeout occured, for instance.

Even if you wrap the signal handler in a sub that passes $error, you will probably have a tough time populating $error with any meaningful information when the timeout occurs. However, since you say you want information "based on the bit of code where the timeout occurred", you can achieve that with caller:

#!/usr/bin/env perl use 5.012; use warnings; # Convenience map for caller return my @ckeys = qw< pack file line sub has_args wantarray evaltext is_require hints bitmask hinthash >; sub Timeout { say "\n===> Signal caught! Call stack below <===="; for (my $i = 1; ;$i++) { my %call; @call{ @ckeys } = caller $i; last if not defined $call{pack}; # Done $call{wantarray} = $call{wantarray} ? 'LIST' : defined $call{wantarray} ? 'SCALAR' : 'VOID'; printf "%20s:%-4d %6s %s\n", @call{qw<file line wantarray sub> +}; } } $SIG{"ALRM"} = \&Timeout; kill ALRM => $$; my @foo = one(); two(); sub one { kill ALRM => $$; } sub two { one('from_two'); }

Output:

===> Signal caught! Call stack below <==== /tmp/uaVo7iA.pl:26 SCALAR (eval) ===> Signal caught! Call stack below <==== /tmp/uaVo7iA.pl:31 SCALAR (eval) /tmp/uaVo7iA.pl:27 LIST main::one ===> Signal caught! Call stack below <==== /tmp/uaVo7iA.pl:31 SCALAR (eval) /tmp/uaVo7iA.pl:35 VOID main::one /tmp/uaVo7iA.pl:28 VOID main::two

Replies are listed 'Best First'.
Re^2: Passing arguments to a function reference
by DrHyde (Prior) on Jul 22, 2013 at 11:01 UTC
    caller() is indeed the correct solution, but I prefer to use Devel::StackTrace, which is a nice wrapper around it. caller() has a hideous interface, Devel::StackTrace has quite a nice one.
      Thanks for all the help guys, I'll look into caller.