Then I made this little test1.pl:package Package1; use fields qw(attr1 attr2 attr3); sub new { my Package1 $self = shift; $self = fields::new($self) unless ref $self; $self->{attr1} = "init_1"; $self->{attr2} = "init_2"; $self->{attr3} = "init_3"; return $self; } 1;
This script failed, complaining there is no field attr4 in the pseudo hash, which is good. Now the next test ...test2.pl:use Package1; use Data::Dumper; my Package1 $p = Package1->new; $p->{attr1} = "set_1"; print $p->{attr1}, "\n"; $p->{attr4} = "set_4"; #this should fail, and did fail
For this second test case, if I uncomment the last print statement, if complains that there is no attr4 in the pseudo hash, although I actually added attr4 already, as you can see in the Data Dumper. On one hand this is good, the checking is still working under ONE definition, (the checking is based on the list I provided in the use field statement). On the other hand, this is really bad, as the data consistancy is now broken. To me, it is crystal clear that, you either make sure that I can not touch the pseudo hash at all, or if you let me touch it, then better make it looks the same from both inside and outside.use Package1; use Data::Dumper; my Package1 $p = Package1->new; $p->[0]->{attr4} = 4; $p->[$p->[0]->{attr4}] = "set_4"; print $p->[0]->{attr4};#the above two steps sunccessfully modified the + internal pseudo hash print Dumper($p);#again proves that I successfully modified the intern +al pseudo hash #print $p->{attr4};#this fails
In reply to Re: (When) Should I 'use fields;'?
by pg
in thread (When) Should I 'use fields;'?
by traveler
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |