February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Through the magic of tie,
an array can act as a scalar. The tie interface can convert the scalar
interface to the array interface. The Tie::Cycle CPAN module uses a scalar to cycle through the values
in an array. The object keeps track of a cursor and advances it on
each access. When it gets to the end, it goes back to the
start:
package Tie::Cycle;
sub TIESCALAR {
my $class = shift;
my $list_ref = shift;
return unless ref $list_ref eq ref [];
my @shallow_copy = map { $_ } @$list_ref;
my $self = [ 0, scalar @shallow_copy, \@shallow_copy ];
bless $self, $class;
}
sub FETCH {
my $self = shift;
my $index = $$self[0]++;
$$self[0] %= $self–>[1];
return $self–>[2]–>[ $index ];
}
sub STORE {
my $self = shift;
my $list_ref = shift;
return unless ref $list_ref eq ref [];
$self = [ 0, scalar @$list_ref, $list_ref ];
}This is handy for giving different CSS classes to alternate rows in an HTML table without complicating the code:
tie my $row_class, "Tie::Cycle", [ qw(odd even) ];
for my $item (@items) {
print qq(<tr class="$row_class">...</tr>);
}This makes it easy to add even more CSS classes without changing the code:
tie my $row_class, "Tie::Cycle", [ qw(red green blue) ];
Read now
Unlock full access