aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-03-18 16:53:14 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2023-03-23 18:03:43 +0100
commitb769feff9ab6b660c55bd3c2a81f9ba0b4169972 (patch)
treec1a5a133b10443b9909ecc0528970f6a2aa4dd17
parent77226b077dde01b4a1c1af69cb1ee1245c099f0e (diff)
downloadperlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.tar.gz
perlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.tar.bz2
perlweeklychallenge-club-b769feff9ab6b660c55bd3c2a81f9ba0b4169972.zip
Challenge 027 task 2
-rwxr-xr-xchallenge-027/jo-37/perl/ch-2.pl60
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);
+}