Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Passing arguments to a function reference

by rjt (Deacon)
on Jul 21, 2013 at 22:04 UTC ( #1045543=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Passing arguments to a function reference
Select or Download Code
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1045543]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-10-23 02:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (123 votes), past polls