develooper Front page | perl.perl5.porters | Postings from November 2022

undeclared named subs/subrefs under strict

Thread Next
From:
breno
Date:
November 21, 2022 18:33
Subject:
undeclared named subs/subrefs under strict
Message ID:
CAHS-WQYANDFwYixdcZ_4vBEV7YgsR2tMnyWe1EzbvE-tgZJ25g@mail.gmail.com
Dear porters,

when sub bar is not declared at all, 'sub foo { bar() }' compiles under
strict/warnings without any issues. Same goes for 'my $x = \&bar'.

Is this by design? I understand why glob refs would not warn or croak but
Is there a reason why explicitly named subroutines that don't exist at
compile time would not yield even a warning until they are actually called?

On a somewhat related note, how would one detect if a named
subroutine/subref was declared or not (it's ok if it was declared but is
empty) at runtime? Right now I'm doing:

sub subref_is_actually_there ($subref) {
    require B;
    my $cv = B::svref_2object($subref);
    return B::class($cv->ROOT) eq 'NULL' && !${ $cv->const_sv };
}

and it seems to work fine but I'm not confident in it. Is there a better or
more readable/portable way? One that would not need to rely on B::*, maybe
just checking if {CODE} is undef?

I looked on perlsub and perlref but could not reach any reasonable
explanation on either, so any help would be greatly appreciated.

Cheers!
garu

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About