24、创建一个名为 Does::ToHash 的角色,该角色将对象的属性转换为哈希。扩展 User 类以使用此角色并进行测试。
创建 Does::ToHash 角色的代码如下:
package Does::ToHash;
use Moose::Role;
sub to_hash {
my $self = shift;
my @attributes = map { $_->name } $self->meta->get_all_attributes;
my %hash;
foreach my $attribute (@attributes) {
my $value = $self->$attribute;
next if ref $value;
$hash{$attribute} = $value;
}
return \%hash;
}
1;
扩展 User 类以使用 Does::ToHash 角色的代码如下:
package User;
use Moose;
with 'Does::ToHash';
use Digest::MD5 'md5_hex';
use namespace::autoclean;
has username => ( is => 'ro', isa => 'Str', required => 1 );
has password => ( is => 'ro', isa => 'Str', writer => '_set_password',);
sub BUILD {
my $self = shift;
$self->_set_password(md5_hex($self->password));
}
sub password_eq {
my ( $self, $password ) = @_;
$password = md5_hex($password);
return $password eq $self->password;
}
__PACKAGE__->meta->make_immutable;
1;
测试代码如下:
use Data::Dumper;
my $user = User->new( username => 'Ovid', password => 'Corinna',);
print Dumper($user->to_hash);
25、编写一个名为 unique 的子例程,该子例程返回数组中的唯一元素,且元素顺序与它们在原始列表中出现的顺序相同,并对其进行测试。
以下是实现该功能的代码:
use Test::Most;
sub unique {
my @array = @_;
my %seen;
my @unique;
foreach my $element (@array) {
push @unique, $element unless $seen{$element}++;
}
return @unique;
}
my @have = unique( 2, 3, 5, 4, 3, 5, 7 );
my @want = ( 2, 3, 5, 4, 7 );
is_deeply \@have, \@want, 'unique() should return unique elements in order';
done_testing;
26、修改 unique 子例程的测试,通过对实际数组和预期数组进行排序,以确保唯一元素是有序的。
可将测试代码修改为:
is_deeply [ sort @have ], [ sort @want ], 'unique() should return unique() elements in order';
这样就对 @have 和 @want 数组都进行了排序,从而保证比较时能确保唯一元素是有序的。
27、编写一个子例程 reciprocal 来计算一个数的倒数,处理非数字输入和除以零的情况,并对其进行测试。
以下是实现该功能的代码:
use Test::Most;
use Carp 'croak';
use Scalar::Util 'looks_like_number';
sub reciprocal {
my $number = shift;
unless ( looks_like_number($number) ) {
croak("Argument to reciprocal() must be a number");
}
unless ($number) {
croak("Illegal division by zero");

最低0.47元/天 解锁文章
872

被折叠的 条评论
为什么被折叠?



