in reply to call subroutine if scalar is changed
I see haj made the same suggestion as I was working on the following code: you can use tie to tie a scalar to a class, where you can customize the "fetch" and "store" events. See also perltie and Tie::Scalar. I tried this with your sample code and it works there as well.
use warnings; use strict; { package Tie::Scalar::Callbacks; sub TIESCALAR { my $class = shift; my %self; @self{qw/ val store_cb fetch_cb /} = @_; return bless \%self, $class; } sub FETCH { my $self = shift; $self->{fetch_cb}->($self->{val}) if $self->{fetch_cb}; return $self->{val}; } sub STORE { my $self = shift; my $val = shift; $self->{store_cb}->($self->{val}, $val) if $self->{store_cb}; $self->{val} = $val; }; sub DESTROY { %{shift()}=() } } tie my $name, 'Tie::Scalar::Callbacks', "foo", sub { print "storing <$_[1]>, was <$_[0]>\n" }; print "name is $name\n"; $name = "bar"; print "name is $name\n"; __END__ name is foo storing <bar>, was <foo> name is bar
Minor update to constructor.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: call subroutine if scalar is changed
by Anonymous Monk on Jun 08, 2019 at 13:26 UTC | |
by choroba (Cardinal) on Jun 08, 2019 at 14:51 UTC | |
by haukex (Archbishop) on Jun 08, 2019 at 20:23 UTC |