use warnings; use strict; { # begin of Car class package Car; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->_init(@_); return $self; } { my @_init_data = qw(name drive body engine_cap); sub _init { my ( $self, $description ) = @_; my %data; @data{@_init_data} = @$description{@_init_data}; %$self = %data; } } sub car_name { my $self = shift; return $self->{name}; } #### sub drive_type { my ( $self, $drive ) = @_; if ($drive) { unless ( $drive =~ /^(?:fwd|rwd|4wd)$/ ) { die "$drive not a valid drive type. Use fwd, rwd or 4wd\n"; } $self->{'drive'} = $drive; } return $self->{'drive'}; } sub body_type { my ( $self, $body ) = @_; if ($body) { unless ( $body =~ /^(?:sedan|wagon|coupe|hatch)$/ ) { die "$body not a valid body type. Use sedan, wagon, coupe or hatch\n"; } $self->{'body'} = $body; } return $self->{'body'}; } sub engine_cap { my ( $self, $cap ) = @_; if ($cap) { $self->{'engine_cap'} = $cap; } return $self->{'engine_cap'}; } #### } # end of Car class my $car = Car->new( { name => 'Toyota', drive => '4wd', body => 'wagon', engine_cap => 2010 } ); print join " " => $car->car_name, $car->drive_type, $car->body_type, $car->engine_cap; print $/; $car = Car->new( { name => 'Kia', drive => 'fwd', body => 'sedan', engine_cap => 2008 } ); print join " " => $car->car_name, $car->drive_type, $car->body_type, $car->engine_cap;