Constructor (object-oriented programming): Difference between revisions

Content deleted Content added
Rubasov (talk | contribs)
Perl: Applied consistent indentation to code sample.
Line 406:
# constructor
sub new {
# class name is passed in as 0th argument
my $class = shift;
# argument
# check if the arguments to the
my $class = shift;
# constructor are key => value pairs
# check if the arguments to the
# constructor are die "$class needs arguments as key => value pairs"
unless (@_ % 2 == 0);
die "$class needs arguments as key => value pairs"
# default arguments
unless (@_ % 2 == 0);
my %defaults;
# default arguments
my %defaults;
# create object as combination of default
# values and arguments passed
my $obj = { %defaults, @_ };
# check for required arguments
%defaults,
die "Need first_name and last_name for Person"
@_,
unless ($obj->{first_name} and $obj->{last_name});
};
 
# check for required arguments
# any custom checks of data
die "Need first_name and last_name for Person"
unless if ($obj->{first_nameage} and&& $obj->{last_nameage} < 18);) { # no under-18s
#die any"No customunder-18 checks of dataPersons";
}
if ($obj->{age} && $obj->{age} < 18)) { # no under-18s
# return object blessed into Person class
die "No under-18 Persons";
bless $obj, }$class;
# return object blessed into Person class
bless $obj, $class;
}
1;