For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > August 2005 > reference to subroutines









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author reference to subroutines
Brent Clark

2005-08-08, 9:04 am

Hi all

Would someone be so kind to explain the following code.

my $subclasses = { 'rejects' => \&_reject_html,
'deferrals' => \&_deferral_html,
'errors' => \&_error_html,
'deliveries' => \&_delivery_html,
'unknown' => \&_unknown_html,
'queue' => \&_queue_html };

The following code comes from the Tom Kistner's exilog
(http://duncanthrax.net/exilog/).

Would someone please share some info on why \& and not just &?
When do you use this?

Thanks in advance.

Brent Clark
Jeff 'japhy' Pinyan

2005-08-08, 9:04 am

On Aug 8, Brent Clark said:

> Would someone be so kind to explain the following code.
>
> my $subclasses = { 'rejects' => \&_reject_html,
> 'deferrals' => \&_deferral_html,
> 'errors' => \&_error_html,
> 'deliveries' => \&_delivery_html,
> 'unknown' => \&_unknown_html,
> 'queue' => \&_queue_html };
>
> Would someone please share some info on why \& and not just &?


If you wrote:

my $subclasses = {
rejects => &_reject_html,
...
};

then the values in the %$subclasses hash would be whatever was returned by
the _reject_html() function. The \&function construct produces a
reference to a subroutine (like you wrote in your subject!) that enables
us to *call* the function at a later time.

my %dispatch_table = (
this => \&abc,
that => \&def,
...
);

if (my $code = $dispatch_table{$state}) {
$code->(@arguments);
}

--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com