package Flashlight; use Carp; use Time::HiRes qw/usleep/; use strict; sub new { my ($class, %options) = @_; my $self = { }; my @required = qw/color/; my @optional = qw/batteries_included type battery_type/; for (@required) { croak "Required named argument $_ was not defined" if not defined $options{$_}; $self->{$_} = $options{$_}; } for (@optional) { $self->{$_} = $options{$_} if exists $options{$_}; } return bless $self, $class; } sub color { my ($self) = @_; return lc $self->{color}; } sub charge_batteries { my ($self, $type) = @_; carp 'Please read the manual!' if defined $type and $type ne $self->{battery_type}; return $self->{batteries_included} = 1; } sub is_on { my ($self) = @_; return $self->{on}; } sub is_off { my ($self) = @_; return ! $self->{off}; } sub on { my ($self) = @_; return undef if not $self->{batteries_included}; $self->{on} = 1; return return 1; } sub off { my ($self) = @_; return $self->{on} = 0; } sub switch { my ($self) = @_; return undef if $self->is_off and not $self->{batteries_included}; return $self->{on} = ! $self->{on} } sub flash { my ($self, $duration) = @_; croak 'Cannot flash while on' if $self->is_on; croak 'Cannot flash for a negative number of seconds' if $duration < 0; carp 'flash() should be used to do nothing at all, changing duration' if defined $duration and $duration == 0; $duration ||= 0.1; $self->on(); usleep $duration; $self->off(); }