Perl - calls to methods that use => - what do they mean?
Archive - Originally posted on "The Horse's Mouth" - 2012-01-16 00:24:09 - Graham EllisHave you seen Perl method calls that look like this?
$present = new box(-smell => "chocolate", noise => "silent");
and wondered "what is all this => stuff" and "what's the - sign for"?
That's a call that could be fairly typical of the sort you'll see in the documentation of any number of standard modules on the CPAN (Comprehensive Perl Archive Network), and it's an API (Application / Programmer Interface) that's designed to be robust, easy to follow, and doesn't add a heavy footprint of variables and names into your program.
Internally, the code:
$present = new box(-smell => "chocolate", noise => "silent");
is the same as:
$present = box::new("box", "-smell", "chocolate", "noise", "silent");
- in other words, run the new sub in the box package, passing in five parameters. The first parameter appears to be redundant (and indeed it is until we start using inheritance), and the other parameters are pairs of attribute names and values.
• => is a synonym for ,
• We can leave the quotes off the attribute names if they are single words before the =>
• The extra - sign ensures that the property name is never going to be a Perl keyword, and the class needs to strip it off if present.
There's a full example, showing this call (and the class / package that implements it) [here] from last week's course. The example is a generic base class with a common setter that handles the various standard ways of passing options (i.e. as above, and also as a reference to a hash).
There's a further example - showing both syntaxes of the constructor and also accessor methods - [here], and the simple class that implements it [here].
Topic covered on our Perl for Larger Projects course and also as appropriate / requested on tailored private courses.