sierrathedog04 has asked for the wisdom of the Perl Monks concerning the following question:

The code for one of the object constructors on CPAN (new Apache::Htgroup) has me confused. Its documentation says that one should construct the object using
$group = new Apache::Htgroup ($path_to_groupfile)

The constructor code is as follows:

package Apache::Htgroup; use strict; use vars qw($VERSION); $VERSION = '0.9'; sub new { my ($class, $groupFile) = @_; my ($self) = {}; bless ($self, $class); $self->{'groupfile'} = $groupFile; return $self; } # End sub new

One calls new with a single parameter $path_to_group_file

Yet the code reads the values of two variables, $class and $groupFile from @_

What is going on? Where does the extra value for $class come from? Any help would be greatly appreciated, as the Llama and Camel books do not contain a clue as to this riddle.

Replies are listed 'Best First'.
Re: Curious Constructor Syntax
by dws (Chancellor) on Feb 16, 2001 at 06:44 UTC
    This is explained in perltoot, but here's the gist of what's going on:

    When you invoke a method via

        method Class(args)
    
    "Class" is passed as the first argument. That's how the new() implementation that you showed knows how to bless the anonymous hash (i.e., what Class to create an instance of). Typically, methods invoked in this fashion return new instances of some class. But this isn't always the case.

    Here's a simple demonstration to show that this behavior isn't limited to new()

    package Foo; sub test { print "test invoked on behalf of ", shift, " with args: @_\n"; } package main; test Foo(47);
    which displays test invoked on behalf of Foo with args: 47
Re: Curious Constructor Syntax
by MeowChow (Vicar) on Feb 16, 2001 at 06:55 UTC
    This is known as indirect object syntax. Camel bible^H^H^H^Hook, pages 295 and 316 :-)

    I should also add that this syntax is somewhat frowned upon, due to the potential ambiguities discussed in the "WARNING" section of perlobj. You only stand to gain by choosing to use the '->' syntax instead. As it states:

    The infix arrow notation using ``->'' doesn't suffer from either of these disturbing ambiguities, so we recommend you use it exclusively.

       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print