1

如何增加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怎么办?我不想为所有这些“等待中的错误”寻找我的代码。

4

2 回答 2

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__
于 2013-04-03T22:37:37.217 回答
1

或者,尝试这样做:

use strict; use warnings;

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

或使用 SCALAR ref(无需像前面的代码片段那样硬编码“路径”):

use strict; use warnings;

$\ = "\n";

use Class::Struct foo => [
  counter => '*$',
];
my $bar = foo->new(counter => 5);
print ++${ $bar->counter };
于 2013-04-03T22:07:07.393 回答