I'm having a hard time understand this behavior (the title is probably not accurate). The Person class below is copied exactly from the CookBook, if I pass a literal parameter, all is fine, but if I pass $1 from a regex, then it got lost. What's going on?
use strict;
use Person;
my $person1 = Person->new;
$person1->name("goodname"); # pass a string literal
print "Good name: ", $person1->name(),"\n"; # the name is printed.
my $person2 = Person->new;
my $s = "badname";
if($s =~ /(.+)/){ #just to match anything
$person2->name($1); # now pass $1, which is "badname"
}
print "Bad name:",$person2->name(),"\n"; # the name is lost!
__END__
Good name: goodname
Bad name:
Here's the person class from the Cookbook:
package Person;
use strict;
use Carp;
use vars qw($AUTOLOAD %ok_field);
# Authorize four attribute fields
for my $attr ( qw(name age peers parent) ) { $ok_field{$attr}++; }
sub AUTOLOAD {
my $self = shift;
my $attr = $AUTOLOAD;
$attr =~ s/.*:://;
return unless $attr =~ /[^A-Z]/; # skip DESTROY and all-cap metho
+ds
croak "invalid attribute method: ->$attr()" unless $ok_field{$attr
+};
$self->{uc $attr} = shift if @_;
return $self->{uc $attr};
}
sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my $parent = ref($proto) && $proto;
my $self = {};
bless($self, $class);
$self->parent($parent);
return $self;
}
1;