summaryrefslogtreecommitdiff
path: root/027/ch2.pl
blob: 25bd6450f15522936e2e8d2cf65b04dc98a1926f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env perl
#
# Write a script that allows you to capture/display historical data. It could be
# an object or a scalar. For example
#
#   my $x = 10; $x = 20; $x -= 5;
#
# After the above operations, it should list $x historical value in order.
################################################################################

use strict;
use warnings;

{
    package Hist;

    require Tie::Scalar;
    our @ISA = qw<Tie::Scalar>;

    sub TIESCALAR {
        return bless \my @histogram, shift;
    }
    sub FETCH {
        my @self = @{shift()};
        printf STDERR "History of values: %s\n", join(", ", @self);
        return @self[@self-1]
    }
    sub STORE {
        my $self = shift;
        my $value = shift;
        push @$self, $value;
    }
}

tie my $x, 'Hist';

$x = 10;
$x = 20;
$x = -5;

my $y = $x;
print "y=$y\n";

$x = 200;
print "x=$x\n";