in reply to Is it possible to distinguish contstants from normal subs?

A constant is nothing more than a subroutine with an empty prototype. Nothing magical. You can distinguish a subroutine with an empty prototype from one that is not prototyped or has a different prototype, but you cannot distinguish a "constant" from a subroutine with an empty prototype, in any form.

-- Randal L. Schwartz, Perl hacker

  • Comment on •Re: Is it possible to distinguish contstants from normal subs?

Replies are listed 'Best First'.
Re: •Re: Is it possible to distinguish contstants from normal subs?
by ariels (Curate) on May 19, 2002 at 06:39 UTC

    The way I read the perldoc, a constant is "a subroutine with an empty prototype" which never changes its return value! There is a clear difference: compare

    sub foo () { 17 }
    with
    sub bar () { rand(10) }
    Deparsing use of both functions in code shows a clear difference in the way Perl treats each one.

Re: •Re: Is it possible to distinguish contstants from normal subs?
by samtregar (Abbot) on May 19, 2002 at 04:09 UTC
    That's disappointing. Perl certainly distinguishes (DB::sub isn't called when they're used, for example) so why shouldn't Perl programmers be able to?

    Dumb idea: could I compile a bit of code and then examine it with B::Utils to figure out if the sub in question is a constant? Hmmmm, don't see why not...

    -sam

      If it's optimized out, probably not. I'd try an experiment with B::Deparse to see what the optree looks like.
        I think it should be possible, but I got stumped trying to figure out how to get the starting OP from an eval"". If I can do that then I can run a simple B::Utils::opgrep() and look for an entersub OP. If there is one, then the subroutine isn't a constant.

        -sam