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
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