http://www.perlmonks.org?node_id=988820


in reply to undef/defined &{$name} while "strict refs"

... I'm not sure why defined/undef &{'walk'} are allowed.

I'm sure others can cite a precise historical development of the usage of strictures, but for me it's a question of expedience.

The use of symbolic references is not discouraged because symbolic references are Evil, but because in certain cases experience has shown them to cause much trouble. These particular cases are foreclosed by  use strict 'refs';

Some cases are both useful and entirely safe. Testing for the definition of a subroutine with
    defined &{ 'subroutine_name' }
is obviously so.

An indispensable use is the very creation of a hard reference in the first place. It's hard to see how some statement like
    my $coderef = \&{ 'subroutine_name' };
is not going to be involved. Indeed, all the following work (and why should they not?)
    my $coderef = \&subroutine_name;
    my $coderef = \&{subroutine_name};
    my $coderef = \&{ 'subroutine_name' };
although  &{subroutine_name} produces an "Ambiguous use of..." warning.

The final case you mention is the potentially very useful  undef &{ 'subroutine_name' };   One can imagine doing this via a hard reference, e.g.
    my $coderef = \&{ 'subroutine_name' };
    undef $$coderef;
or some such roundabout implementation (that one doesn't actually work, BTW), but what would be the point? After all, it's the name of the subroutine that ultimately has to be undefined; just going to the address of the actual code and scribbling something over it (a return? a jump to an exception?) would not seem to gain you very much.

Anyway, my USD0.02.

Replies are listed 'Best First'.
Re^2: undef/defined &{$name} while "strict refs"
by anazawa (Scribe) on Aug 21, 2012 at 19:49 UTC

    Your suggestion is insightful. We need to manipulate symbol table carefully. Though I was under the impression that the following causes autovivification, it doesn't:

    my $bool = defined &{ 'foo::bar' };
    c.f.
    my $namespace = do { no strict 'refs'; \%{"foo::"} }; my $bool = exists $namespace->{bar} && defined *{ $namespace->{bar} }{ +CODE};
    In fact, the following causes autovivification:
    no strict 'refs'; my $before = exists $foo::{bar}; # false my $bool = defined *{ 'foo::bar' }{CODE}; my $after = exists $foo::{bar}; # true
    I misunderstood defined &{ 'foo::bar' } cause autovivification. That's why you think defined &{ 'foo::bar' } is safe, right?

    I agree the name of the subroutine has to be undefined. We are allowed to avoid "no warnings redefine" when we use undef &{ 'foo::bar' }.
    undef &{ 'foo::bar' }; no strict 'refs'; *{ 'foo::bar' } = sub {};
    c.f.
    no strict 'refs'; no warnings 'redefine'; *{ 'foo::bar' } = sub {};
    By the way, the following should work:
    my $coderef = \&{ 'subroutine_name' }; #undef $$coderef; # typo ? undef &{ $coderef };
    Thanks for your comment :)