sub read_file {
open("person_file", "<person_data.txt");
my $class = shift;
my @people;
while (<person_file>) {
# entries are delimited by a | character
# format is
# firstname|lastname|streetaddress|town|state|zipcode
my $line = $_;
chomp($line);
my @broken_line = split(/\|/, $line);
print Dumper(@broken_line);
my $curr_person = new Person;
$curr_person->set_first_name($broken_line[0]);
$curr_person->set_last_name($broken_line[1]);
$curr_person->set_street_address($broken_line[2]);
$curr_person->set_town($broken_line[3]);
$curr_person->set_state($broken_line[4]);
$curr_person->set_zip_code($broken_line[5]);
print $curr_person->get_full_name(), "\n",
$curr_person->get_full_address(), "\n";
push(@people, $curr_person);
}
print "\n\n\n";
foreach my $person (@people) {
print $person->get_full_name(), "\n", $person->get_full_address(), "\n";
}
print Dumper(@people);
print "\n\n\n";
close("person_file");
return \@people;
}
这是输出:
$VAR1 = 'K';
$VAR2 = 'M';
$VAR3 = '4th St';
$VAR4 = 'New York';
$VAR5 = 'NY';
$VAR6 = '10001';
K M
4th St
New York, NY 10001
$VAR1 = 'C';
$VAR2 = 'G';
$VAR3 = '3 Fifth Ave';
$VAR4 = 'New York';
$VAR5 = 'NY';
$VAR6 = '10003';
C G
3 Fifth Ave
New York, NY 10003
C G
3 Fifth Ave
New York, NY 10003
C G
3 Fifth Ave
New York, NY 10003
$VAR1 = bless( do{\(my $o = 'Person')}, 'Person' );
$VAR2 = bless( do{\(my $o = 'Person')}, 'Person' );
当我读取文件时,第一块输出发生在循环中。第二个是在第二个循环中,我检查数组只是为了查看是否所有变量都正确,但它们不是。所以我发现的问题是 $curr_person 不会收到新的内存位置,即使它超出了范围或被称为新的人;并将与 $people[0] 等共享内存位置,这样人们中的所有元素都将被 $curr_person 中的任何内容覆盖。
有没有办法让 $curr_person 在循环的每次迭代中获得一个新的内存位置?
谢谢
人物类:
package Person;
use strict;
use warnings;
my $first_name;
my $last_name;
my $street_address;
my $town;
my $state;
my $zip_code;
my $unique_id;
sub new
{
my $instance = shift;
bless \$instance, "Person";
}
这是我第一个非练习(5 行)Perl 项目,我仍在尝试理解 Perl 中 OOP 的语法。