package TDP::RewriteSettlementFiles::Common; use 5.008008; use strict; use Exporter qw{import}; our @EXPORT_OK = qw{mk_mutator_accessor fatal_error}; use Carp; use Readonly; use Switch; our $VERSION = '0.00_01'; $VERSION = eval $VERSION; # see L sub fatal_error { local $Carp::CarpLevel = 1; Carp::croak ( (caller(1))[3] . '(): ' . shift() ); } sub _mk_plain_closure { my ($hash_key) = @_; return sub { my ($self, $value) = @_; if (@_ > 1) { $self->{$hash_key} = $value; } return $self->{$hash_key}; }; } sub _mk_array_validated_closure { my ($hash_key, $field_name, $values_aref) = @_; my %valid_values = map { $_ => {} } @$values_aref; return sub { my ($self, $value) = @_; if (@_ > 1) { fatal_error("invalid value for $field_name") if !exists $valid_values{$value}; $self->{$hash_key} = $value; } return $self->{$hash_key}; }; } sub mk_mutator_accessor { my ($pkg, $field_name, $valid_values_ref) = @_; my $slot = "$pkg\::$field_name"; ## building the closure outside the "no strict 'refs'" block ## to avoid subtle side effects; using $slot for the key to ## avoid namespace collision with XML::SAX::Base. my $closure = defined $valid_values_ref ? _mk_array_validated_closure($slot, $field_name, $valid_values_ref) : _mk_closure($slot); { no strict 'refs'; *$slot = $closure; } } 1;