3 ms·
Perl 5 has dynamic scoping for backward compatibility with Perl 4, which had only dynamic scoping, and not only that, it botched it so that this code didn't wor
by kragen 16y ago
Perl 5 has dynamic scoping for backward compatibility with Perl 4, which had only dynamic scoping, and not only that, it botched it so that this code didn't work right:
sub greet {
local ($who) = @_;
print "hello, $who\n";
}
$who = "world";
&greet($who);
This would print, "hello, " with a newline, due to a design bug called "variable suicide", which has been fixed in newer Perls.
Needless to say, this made the extract-subroutine refactoring quite a bit more trouble in Perl 4.
- avar 16y agoIt doesn't just have it for backwards compatibility, it's still a very useful feature in some cases: sub foo { local $ENV{HOME} = "/foo/bar"; Code::I::Don't::Own(); } foo(); Having dynamic scope here ensures that the foreign code will use the environment I want without me having to alter it.
- draegtun 16y agoPerl 6 also has dynamic scoping. But I don't think they kept it just for backward compatibility with Perl 4 & 5 :) Here is another example where dynamic scoping can indeed be very useful: sub bar { 'bar' } sub baz { bar() } sub foo { no warnings 'redefine'; local *bar = sub { 'My Bar' }; baz(); } say foo(); # => 'My Bar' say baz(); # => 'bar'