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

Re: re-calling called functions

by tsee (Curate)
on Oct 28, 2006 at 18:42 UTC ( #581100=note: print w/ replies, xml ) Need Help??


in reply to re-calling called functions

Now, I suggest you never, ever, ever do this. A subroutine should not knwo about its calling context aside from what wantarray or the Want module provide. It's good for some fun hacking, but it boils down to being an evil hack. Rethink your algorithm.

That being said, it is possible in Perl. (No surprise, right?) It's just that it doesn't make any sense. Additionally, there are various corner cases which will break this.

The following code kind of does what you want. I suggest you read up on the caller() function. Also, you can't call the calling subroutine with its original arguments.

#!/usr/bin/perl use strict; use warnings; sub _gotocaller { my $i = 2; while (1) { my ($pkg, $file, $line, $sub) = caller($i); if (not defined $pkg) { # no caller return; } elsif ($sub =~ /::__ANON__$/ or $sub eq '(eval)') { $i++; } else { no strict; goto &{"$sub"}; die; } } } my $x = 1; sub foo { print "foo: $x\n"; if ($x < 10) { print join("|", caller(1)), "\n"; _gotocaller() or die "shouldn't be reached if there was an enc +losing subroutine!"; } } sub bar { print "bar: $x\n"; foo($x++); } bar();

Note that there are many things wrong with this code and I even thought about discarding the post when I looked at it again. To name just a few: symbolic references, goto &sub (which wouldn't be so bad if it wasn't used in conjunction with symbolic references and caller()), breaks for anonymous subs and eval's (or rather: calls the named sub that called the anonymous sub or eval block), etc.

Please, promise to not use this code. :/

Steffen


Comment on Re: re-calling called functions
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-09-19 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (151 votes), past polls