We all have those things that we can't just grasp despite extensive research and testing. For me, it's the real purpose and benefit of a callback. I'm asking this question in hopes someone can make it just *click*, like Randal Schwartz's book "Learning Perl Objects, References and Modules" did for references.

My main focus is on trying to understand how 'asynchronous' (non-blocking) callbacks work. I've read they are used to offput work so that the main program can continue to work. I can't find any small enough examples that make sense. I'm imagining this would be used with fork() or threading or the like, but I just can't put it all together.

Here's a tiny code snip of what I believe is a true callback, but how do I make it function in a "do something over there so I (main) can proceed with other work"?

#!/usr/bin/perl use warnings; use strict; sub callback { for my $n (1..3){ print "callback: $n\n"; sleep(1); } } sub my_caller { my ($i, $func) = @_; print "caller calling callback\n"; &$func(); } # main my_caller(10, \&callback); for my $n (10..12){ print "main: $n\n"; sleep(1) }

I know they are used in GUI programming to wait for say, a button click, but I haven't found any examples in any languages I know well enough to understand what is happening, and how.

Would anyone be kind enough as to perhaps give an example or two to help me get over this hump of confusion? I think if I understand a real-life working purpose of a callback, I can apply other aspects to their use (such as triggering different actions etc) on my own.

Thanks,

-stevieb


In reply to Understanding callbacks by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.