J
J Krugman
I'm OK with coding objects, but I find tied variables a bit
terrifying...
Anyway, it is common to implement objects as hashes (or rather as
references to hashes). My question is, is it possible to use a
(reference to a) tied hash instead of a (reference to a) regular
hash for this? I would have thought yes, but if I try to use a
tied hash instead of a regular hash I get this strange error
Can't return a temporary from lvalue subroutine...
This happens when I attempt to assign to an lvalue method (which
works fine if I don't use the tied hash).
What "temporary" is the error message referring to? Is there a
work around?
I give the relevant code below.
TIA,
jill
package Helper;
use Tie::Hash;
our @ISA = 'Tie::StdHash';
sub STORE {
my ($self, $key, $value) = @_;
warn "storing value $value under key $key\n";
$self->{$key} = $value;
}
1;
__END__
package My_Class;
use Helper;
sub new {
my $class = shift;
my %self = ();
tie %self, 'Helper'; # OK if this line is commented out
return bless \%self, $class;
}
sub var : lvalue {
my $self = shift;
$self->{_var_} = shift if @_;
$self->{_var_};
}
1;
__END__
use My_Class;
my $v = My_Class->new();
$v->var = 42; # fatal error
terrifying...
Anyway, it is common to implement objects as hashes (or rather as
references to hashes). My question is, is it possible to use a
(reference to a) tied hash instead of a (reference to a) regular
hash for this? I would have thought yes, but if I try to use a
tied hash instead of a regular hash I get this strange error
Can't return a temporary from lvalue subroutine...
This happens when I attempt to assign to an lvalue method (which
works fine if I don't use the tied hash).
What "temporary" is the error message referring to? Is there a
work around?
I give the relevant code below.
TIA,
jill
package Helper;
use Tie::Hash;
our @ISA = 'Tie::StdHash';
sub STORE {
my ($self, $key, $value) = @_;
warn "storing value $value under key $key\n";
$self->{$key} = $value;
}
1;
__END__
package My_Class;
use Helper;
sub new {
my $class = shift;
my %self = ();
tie %self, 'Helper'; # OK if this line is commented out
return bless \%self, $class;
}
sub var : lvalue {
my $self = shift;
$self->{_var_} = shift if @_;
$self->{_var_};
}
1;
__END__
use My_Class;
my $v = My_Class->new();
$v->var = 42; # fatal error