in reply to Trying to Understand Callback(s)
...but I don't really quite get the idea of callbacks, and particularly I don't understand the syntax.
Well, it's not just quite like with a phone - you ring up somebody, they hang up and call you - but rather a way to parametrize a subroutines execution chain via a subroutine reference (like a function pointer). The called sub may have been compiled into any context, and the compilation rules of that context apply. And what ikegami said.
I don't really get the first line of the get_callback routine either, when nothing appears to be being passed across
It gets something passed across but discards it.
A sub routine called as a method ($thingy->routine(@args)) by something ($thingy - irrelevant whether $thingy is a literal, a blessed reference, a scalar holding a string, or an expression which resolves to a package or a blessed reference) gets passed the invocant as its first parameter in @_.
So, having this preamble
sub routine { my($thingy, $tx) = @_; # $thingy is not used print "routine: $tx\n"; } my $ref = \&routine; # take a reference to the sub my $pkg = "main"; my $obj = bless do { \my $x }; # we could also say... # my $pkg = __PACKAGE__; # ...to get any package we are in in compile time
the following call expressions are all equivalent:
# method calls main->routine("foo"); main->$ref ("foo"); $pkg->routine("foo"); $pkg->$ref ("foo"); $obj->routine("foo"); $obj->$ref ("foo"); # or even (join'',map{chr}(109,97,105,110))->routine("foo"); __PACKAGE__->$ref("foo"); (bless \my $x)->$ref("foo"); # function calls routine ('main', "foo"); $ref -> ('main', "foo"); routine ($pkg, "foo"); $ref -> ($pkg, "foo"); &$ref ($pkg, "foo"); routine ($obj, "foo"); # etc.
More on differences between subroutine calls either as function or method: perlsub, perlmod, perlref.
The expression
my (undef, $thing) = @_;
is just a fancy way of saying
shift @_; # drop first element of argument list my ($thing) = @_;
The subroutine get_callback you quoted just seems not to care at all about it's invocant, but nonetheless expects to be called as a method. Hmm, code smell...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Trying to Understand Callback(s)
by DanielSpaniel (Scribe) on Nov 24, 2017 at 01:14 UTC | |
by Laurent_R (Canon) on Nov 24, 2017 at 21:32 UTC |