Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: re-calling called functions

by tsee (Curate)
on Oct 28, 2006 at 18:42 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-16 21:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found