Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re^3: Defining a sub within a sub: OK?

by moritz (Cardinal)
on Oct 14, 2009 at 23:06 UTC ( #801236=note: print w/replies, xml ) Need Help??


in reply to Re^2: Defining a sub within a sub: OK?
in thread Defining a sub within a sub: OK?

* The reasoning behind sub NAME { } constructs being realized early is so that you can call subroutines even if their definition is "later" in the code.

That's mostly true, but not very precise.

If a subroutine is defined after it is called, the call has to use parenthesis. If it doesn't, it's interpreted as a string literal (or as an error if strict subs are in effect).

$ perl -E 'say 1, foo; sub foo { 3 }' 1foo $ perl -E 'sub foo { 3 }; say 1, foo' 13 $ perl -E 'say 1, foo(); sub foo { 3 }' 13

However it the call uses parenthesis, there's no need it has to be know at compile time at all:

$ perl -E 'eval "sub foo { 3 }"; say 1, foo();' 13

But I think for this discussion it's more important to ask when the lexical pad of sub a is being built and destroyed. As long as the a is not part of the call chain, $x is in no lex pad, and sub b can't work in a meaningful way.

Perl 6 - links to (nearly) everything that is Perl 6.

Replies are listed 'Best First'.
Re^4: Defining a sub within a sub: OK?
by ikegami (Pope) on Oct 15, 2009 at 01:19 UTC

    If a subroutine is defined after it is called, the call has to use parenthesis.

    Not quite. If a subroutine is declared after it is called, the call has to use parenthesis. You can always define it afterwards.

    >perl -wle"sub foo; foo; sub foo { print 'Hi!' }" Hi!

    Granted, it's very rare for a subroutine to be declared somewhere other than when it's being defined.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://801236]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (12)
As of 2019-06-26 17:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (110 votes). Check out past polls.

    Notices?