sds
sds

Reputation: 60054

Perl: how to increment a Class::Struct field?

How do I increment a field in a Class::Struct object?

For now I am stuck with

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

I wonder if there is something more expressive than the last line (the obvious $bar->counter++ results in Can't modify non-lvalue subroutine call).

EDIT: of course, I am not interested in $bar->[0]++ et al - what if I add a field before counter? I don't want to have to hunt my code for all such "bugs-in-waiting".

Upvotes: 1

Views: 348

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185590

Alternatively, try doing this :

use strict; use warnings;

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

or using a SCALAR ref (no need to hard-code the "path" like the previous snippet) :

use strict; use warnings;

$\ = "\n";

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

Upvotes: 1

Sinan Ünür
Sinan Ünür

Reputation: 118156

You can add an increment method to 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__

Upvotes: 6

Related Questions