Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Why callbacks?

by pileofrogs (Priest)
on Mar 30, 2007 at 17:19 UTC ( [id://607533]=note: print w/replies, xml ) Need Help??


in reply to Re: Why callbacks?
in thread Why callbacks?

Woah... doesn't my_fetch_callback go out of scope before you can call it?

Replies are listed 'Best First'.
Re^3: Why callbacks?
by Joost (Canon) on Mar 30, 2007 at 17:32 UTC
    Named subroutines never go out of scope; they're global - bound to a package just like global variables.

    Anonymous subrefs can go out of scope, just like any other variable, but, just like any other variable, you can pass them around:

    sub call { my ($arg1,$arg2) = @_; my $callback = sub { my ($arg3) = @_; return $arg1 + $arg2 + $arg3; }; call_func_needing_callback($callback); } # or even sub call { my ($arg1,$arg2) = @_; call_func_needing_callback( sub { my ($arg3) = @_; return $arg1 + $arg2 + $arg3; }); }

    Also note that there are scoping issues with defining named closures within other subroutines (this probably has to do with named subroutines being global), while unnamed subroutines/closures will work as real lexical closures.

Re^3: Why callbacks?
by Fletch (Bishop) on Mar 30, 2007 at 17:27 UTC

    I presume this was asked before I moved the brace, but even then no. The scalar would have (which is why I made the correction), but the subroutine sticks around (they're not lexically declared). Had I done this:

    { my $returned_data = []; my $callback = sub { push @{ $returned_data }, $_[0] }; } something_wanting_callback( $callback );

    Then yes, that coderef would have gone out of scope.

      So, all subrutines are in effect global? Huh.. I didn't know that.

      -Pileofrogs

      In Other News:
      Whoever keeps downvoting me, please tell me what it is that you don't like... I can't get better if you don't tell me what's wrong...

        Named subs all reside in the symbol table of the active package when they're declared (if the name is unqualified, that is; it's also possible to stick a sub into another package's namespace by fully qualifying the name: sub Other::Package::foo { ... }). It's also possible to get a sub which is only useable within a particular lexical scope by storing a coderef in a lexical scalar.

        { my $private_sub = sub { print "I'M IN UR SCOPE HIDIN UR LEXICALZ\n" } ## Can be called here $private_sub->( ); } ## Can't call it here

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2024-04-20 05:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found