Localised sub?

M

Matthew Braid

Hi all,

I was just playing around a bit (chewing time before long weekend :) ) when I
came across a bit of code that doesn't work but I can't figure out why. Running
this:

sub foo {
print "1\n";
}
{
my $oldfoo = \&foo;
print "MAIN FOO IS ", \&main::foo, "\n";
local *foo;
print "MAIN FOO NOW ", \&main::foo, "\n";
sub foo {
print "2\n";
$oldfoo->();
}
print "MAIN FOO NOW ", \&main::foo, "\n";
print "1...\n";
foo(); # Line 15
}
print "2...\n";
foo();
__END__

Results in:

MAIN FOO IS CODE(0x812583c)
MAIN FOO NOW CODE(0x81232a0)
MAIN FOO NOW CODE(0x81232a0)
1...
Undefined subroutine &main::foo called at test.pl line 15.

So now I'm wondering how to access a subroutine with a 'local' name. Is it even
possible? I was thinking this might be useful for overriding a sub call inside
another sub call without overriding the whole outer sub (yikes - I shouldn't
drink beer at lunch!) eg:

sub bar {
print "BAR 1\n";
foo();
print "BAR 2\n";
}
sub foo {
print "FOO!\n";
}
bar(); # Do everything normally
{
local *foo;
sub foo {
print "NEW FOO!\n";
}
bar(); # Override the internal call to foo
}
bar(); # Normal again
__END__

To get the output:

BAR 1
FOO!
BAR 2
BAR 1
NEW FOO!
BAR 2
BAR 1
FOO!
BAR 2

Does this make sense or am I an idiot?

MB
 
M

Matthew Braid

Abigail said:
}} MAIN FOO IS CODE(0x812583c)
}} MAIN FOO NOW CODE(0x81232a0)
}} MAIN FOO NOW CODE(0x81232a0)
}} 1...
}} Undefined subroutine &main::foo called at test.pl line 15.

Yes, that's because the subs are created at compile time, and at
runtime you localize the glob.

}} So now I'm wondering how to access a subroutine with a 'local' name. Is it even
}} possible?

Use the following in the inner block, instead of 'sub foo { ... }':

*foo = sub {
print "2\n";
$oldfoo -> ();
};

Abigail

That's my new thing learnt for today - thanks :)

MB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top