1#!./perl 2 3BEGIN { 4 chdir 't' if -d 't'; 5 require './test.pl'; 6 set_up_inc('../lib'); 7 require Config; 8} 9 10use v5.36; 11use feature 'class'; 12no warnings 'experimental::class'; 13 14# reader accessors 15{ 16 class Testcase1 { 17 field $s :reader = "the scalar"; 18 19 field @a :reader = qw( the array ); 20 21 # Present-but-empty parens counts as default 22 field %h :reader() = qw( the hash ); 23 } 24 25 my $o = Testcase1->new; 26 is($o->s, "the scalar", '$o->s accessor'); 27 ok(eq_array([$o->a], [qw( the array )]), '$o->a accessor'); 28 ok(eq_hash({$o->h}, {qw( the hash )}), '$o->h accessor'); 29 30 is(scalar $o->a, 2, '$o->a accessor in scalar context'); 31 is(scalar $o->h, 1, '$o->h accessor in scalar context'); 32 33 # Read accessor does not permit arguments 34 ok(!eval { $o->s("value") }, 35 'Reader accessor fails with argument'); 36 like($@, qr/^Too many arguments for subroutine \'Testcase1::s\' \(got 1; expected 0\) at /, 37 'Failure from argument to accessor'); 38} 39 40# Alternative names 41{ 42 class Testcase2 { 43 field $f :reader(get_f) = "value"; 44 } 45 46 is(Testcase2->new->get_f, "value", 'accessor with altered name'); 47 48 ok(!eval { Testcase2->new->f }, 49 'Accessor with altered name does not also generate original name'); 50 like($@, qr/^Can't locate object method "f" via package "Testcase2" at /, 51 'Failure from lack of original name accessor'); 52} 53 54done_testing; 55