Example: Implementation of Car in Perl

Listing 18.1 shows how a simple car could be represented in Perl. This listing should be saved as Car.pm.

To create a class in Perl, a constructor must bless a reference into the class. What this means is a reference (it doesn't matter what type, most people use hash references) is going to be created within the new subroutine. The bless function will take that reference and associate it with the class as an instance. The new subroutine should then return that reference.

Listing 18.1. First Part of the Car Class
 1: #!/usr/bin/perl -w 2: 3: use strict; 4: package Car; 5: 6: my $model_name = "RoadPerl"; 7: my $vin = 1; 8: 9: sub new { 10: my $car = { 11: vin => $vin++, 12: rpm => 0, 13: }; 14: bless $car; ...

Get SAMS Teach Yourself Perl in 24 Hours THIRD EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.