diff options
| author | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-03-18 16:53:14 +0100 |
|---|---|---|
| committer | Jörg Sommrey <28217714+jo-37@users.noreply.github.com> | 2023-03-23 18:03:43 +0100 |
| commit | b769feff9ab6b660c55bd3c2a81f9ba0b4169972 (patch) | |
| tree | c1a5a133b10443b9909ecc0528970f6a2aa4dd17 | |
| parent | 77226b077dde01b4a1c1af69cb1ee1245c099f0e (diff) | |
| download | perlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.tar.gz perlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.tar.bz2 perlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.zip | |
Challenge 027 task 2
| -rwxr-xr-x | challenge-027/jo-37/perl/ch-2.pl | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/challenge-027/jo-37/perl/ch-2.pl b/challenge-027/jo-37/perl/ch-2.pl new file mode 100755 index 0000000000..613a4a1ec2 --- /dev/null +++ b/challenge-027/jo-37/perl/ch-2.pl @@ -0,0 +1,60 @@ +#!/usr/bin/perl + +use v5.16; +use warnings; +use experimental qw(signatures postderef); + +### + +# Import "record" and "history". +HistoryScalar->import(); + +my $x; +# Start recording. +record($x); + +# Assign and retrieve. +$x = 1; +say "x: $x"; + +# Assign several values and retrieve the current. +$x = ($x * 3) % 7 for (0..4); +say "x: $x"; + +# Show the history. +say "x's history: ", join ', ', history($x); + + +### Implementation + +package HistoryScalar; + +# Minimal TIESCALAR interface. +sub TIESCALAR ($class) { + bless [], $class; +} + +sub FETCH ($self) { + $self->[-1]; +} + +sub STORE ($self, $value) { + push $self->@*, $value; +} + +# Tie the argument to this package. +sub record { + tie $_[0], __PACKAGE__; +} + +# Recall the history. +sub history { + tied($_[0])->@* +} + +# Export "record" and "history" into the caller's package. +sub import ($class) { + my $caller = caller(); + no strict 'refs'; + *{"$caller\::$_"} = \&{"$class\::$_"} for qw(record history); +} |
