The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Tie::Scalar::Callback - a tied scalar which executes a callback everytime it is used

VERSION

version 0.05

SYNOPSIS

  use Tie::Scalar::Callback;

  # this coderef doubles the scalar's value everytime it's fetched
  my $coderef = sub {
    my ($self, $event, $val) = @_;

    if ($event eq 'STORE')
    {
      $self->{val} = $val;
    }
    elsif ($event eq 'FETCH')
    {
      my $old_val = $self->{val};
      $self->{val} *= 2;
      return $old_val;
    }
    else # DESTROY
    {
      undef $self;
    }
  };

  tie(my $doubler, 'Tie::Scalar::Callback', $coderef, 1);

  print $doubler; 1
  print $doubler; 2
  print $doubler; 4

DESCRIPTION

Tie::Scalar::Callback is a class for creating tied scalars which execute a callback everytime an event occurs on the scalar. There are three types of event:

  • STORE ($self, 'STORE', $value)

    Called anytime a value is assigned to the scalar.

  • FETCH ($self, 'FETCH')

    Called anytime the scalar's value is retrieved.

  • DESTROY ($self, 'DESTROY')

    Called on object destruction.

See the synopsis for an example coderef which handles these events.

INTERNALS

Tie::Scalar::Callback objects are just anonymous hashes. The coderef is stored in $self->{sub} and the current value of the scalar in $self->{val}.

ACKNOWLEDGEMENTS

Thanks to brian d foy for coming up with the idea for this module.

SEE ALSO

AUTHOR

David Farrell <dfarrell@cpan.org>

COPYRIGHT AND LICENSE

This software is Copyright (c) 2016 by David Farrell.

This is free software, licensed under:

  The (two-clause) FreeBSD License