【问题标题】:New perl object overwrites data of previous object新的 perl 对象覆盖前一个对象的数据
【发布时间】:2014-02-13 03:52:12
【问题描述】:

当我创建 2 个单独的 Perl 对象实例时,第二个将覆盖第一个的数据。我是 OO Perl 的新手,所以我想我在如何处理类中的 $self 变量方面缺少一些基本的东西。为什么 $ptr2 对象的数据会覆盖 $ptr1 对象的数据?这可能是 Perl 专家给出的简单 1 分钟回答,但我一直在努力解决这个问题。我的实际应用程序应该从不同来源获取一堆数据并运行一些数据分析,所以下面我有一个简化版本来显示手头的问题。

我确实检查了与以下同一主题相关的one other question,但它似乎与我的问题不同。

以下是我在课堂上的内容:

package TestClass;

sub new {
  my ($object, $file) = @_;
  my $class = ref($object) || $object;
  my $self = { myfile => $file, };
  bless($self, $class);
  return($self);
}
# grabs key-val pairs from file
sub getFileData {
  my($self) = @_;
  open (FILE, "$self->{myfile}" ) or die "Cannot open\n";
  while (my $curline = <FILE>) {
    my @fields = split(/\s+/,$curline);
    $self{$fields[0]} = $fields[1];
  }
  close FILE;
}
# prints key-val pairs to stdout
sub printFileData {
  my($self) = @_;
  foreach my $key (keys %self) {
    print "$key -> $self{$key}\n";
  }
}
1;

下面是我如何调用类对象:

use TestClass;

my $ptr1 = TestClass->new("test1.txt");
my $ptr2 = TestClass->new("test2.txt");

$ptr1->getFileData();
print "This is correct for test1.txt\n";
$ptr1->printFileData();

$ptr2->getFileData();

print "This is wrong for test1.txt, test2.txt overwrote test1.txt\n";
$ptr1->printFileData();
$ptr2->printFileData();

test1.txt 和 test2.txt 分别有单行 'VAL1 1' 和 'VAL1 2'。

脚本的输出如下:

This is correct for test1.txt
VAL1 -> 1
This is wrong for test1.txt, test2.txt overwrote test1.txt
VAL1 -> 2
VAL1 -> 2

【问题讨论】:

  • use strict; use warnings; 会为您找到这些错误。

标签: perl class oop object overwrite


【解决方案1】:

在 TestClass.pm 中,将所有 $self{$key} 实例替换为 $self-&gt;{$key}(第 16 和 24 行),并将 %self 替换为 %$self(第 23 行)。

您的输出将如下所示:

This is correct for test1.txt
myfile => test1.txt
VAL1 => 1
This is wrong for test1.txt, test2.txt overwrote test1.txt
myfile => test1.txt
VAL1 => 1
myfile => test2.txt
VAL1 => 2

顺便说一句,如果您use strict; Perl 会为您捕获这些错误。

【讨论】:

  • 非常感谢!我知道我在做这样愚蠢的事情。我想 self 是对哈希的引用,而不是哈希本身。
  • 我也试过'use strict;'但这并没有标记这个特殊问题。
  • 我明白了:Global symbol "%self" requires explicit package name at cl.pl line 43. Execution of cl.pl aborted due to compilation errors.
  • 你又是对的。我在调用脚本中有它,而不是在包 .pm 文件中。我解决了这个问题,我看到了同样的信息。谢谢。
猜你喜欢
  • 2018-01-20
  • 1970-01-01
  • 2016-05-08
  • 2017-08-12
  • 2017-04-06
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多