Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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. :/


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://581100]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2018-03-18 01:05 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (228 votes). Check out past polls.