Perl:如何增加Class :: Struct字段?

时间:2013-04-03 21:54:24

标签: perl class

如何增加Class::Struct对象中的字段?

现在我被困了

use Class::Struct foo => [
  counter => '$',
];
my $bar = foo->new(counter => 5);
$bar->counter($bar->counter()+1);

我想知道是否有比最后一行更具表现力的东西($bar->counter++中显而易见的Can't modify non-lvalue subroutine call结果。)

编辑:当然,我对$bar->[0]++等不感兴趣 - 如果我在counter之前添加一个字段怎么办?我不想为所有这些“等待中的错误”搜索我的代码。

2 个答案:

答案 0 :(得分:6)

您可以向increment添加foo方法:

#!/usr/bin/env perl

package foo;

use strict; use warnings;

sub increment_counter {
    my $self = shift;
    my $val = $self->counter + 1;
    $self->counter($val);
    return $val;
}

package main;

use 5.012;
use strict;
use warnings;

use Class::Struct foo => [
  counter => '$',
];

my $bar = foo->new(counter => 5);

$bar->increment_counter;

say $bar->counter;

__END__

答案 1 :(得分:1)

或者,尝试这样做:

use strict; use warnings;

use Class::Struct foo => [
  counter => '$',
];
my $bar = foo->new(counter => 5);
print ++$bar->[0];

或使用SCALAR引用(不需要像前一个代码片段那样对“路径”进行硬编码):

use strict; use warnings;

$\ = "\n";

use Class::Struct foo => [
  counter => '*$',
];
my $bar = foo->new(counter => 5);
print ++${ $bar->counter };