
Laurent_R
Veteran
/ Moderator
Dec 2, 2012, 2:20 AM
Post #3 of 6
(6011 views)
|
Re: [gevni] Confused in understanding function and it call!!
[In reply to]
|
Can't Post
|
|
Same idea as Bill. 1. You should probably remove the prototype (the '(&@)' part) in the function definition unless you know damn well why you are doing it. 2. &$func is a code ref or a reference to a function. It is passed to the apply_index function, which will be able to use it. This is what if usually called a callback function. You have probably already met such callbacks, although possibly without really noticing. The most common example is when you are using the sort function. If you want to sort an array or a hash by its values, you can write something like:
my @sorted_result = sort {$a <=> $b} @unsorted; or, maybe:
my @sorted_result = sort {$day_income{$a} <=> $day_income{$b}} keys %day_income; In both cases, you are really passing a reference to some code to the sort function, so that it knows what comparison subroutine or code it should use for sorting your data. This is the possibility to do that which makes the sort function so useful: sort will do the sorting using its own efficient sorting algorithm and applying your own sorting criteria. This is just an example which is built-in within Perl. You can also define your own functions to be passed to other functions, making your code far more flexible. For example, you can write a generic function in a package or a module that makes some complicated calculation. But you may want the result of this calculation to be printed out to the screen, stored into some variable, data structure or object, returned to the calling function, checked for consistency with other data or even used for some further calculation. Rather than trying to plan every possible use that the user of your function will want to apply, you can simply pass to the generic function a reference to another (used-defined) function, that the generic function will apply to the results of its own calculation. This is what happens in the code snippet you have posted. The "{push @index, @_}" code ref is passed to the apply_index function, which does not know what this code is doing, but will blindly apply it to the result of its own computations when executing the "&$func" code.
|