TimelogTxt/Stack.pm untested

filter: Statementstmt 0.0% 0 / 59 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 103 CC 11 SCAR 23.6
CC
11
Cov
0%
drop
30.0
new
6.0
pop
6.0
CRAP 10.5
1 package App::TimelogTxt::Stack;
2  
3 use warnings;
4 use strict;
5 use autodie;
6  
7 our $VERSION = '0.22';
8  
9 sub new
10 {
11 my ($class, $file) = @_;
12 die "No file specified.\n" unless $file;
13 return bless { file => $file }, $class;
14 }
15  
16 sub clear
17 {
18 my ($self) = @_;
19 unlink $self->{file};
20 return;
21 }
22  
23 sub push
24 {
25 my ($self, $task) = @_;
26 open my $fh, '>>', $self->{file};
27 print {$fh} $task, "\n";
28 return;
29 }
30  
31 sub pop
32 {
33 my ($self) = @_;
34 return unless -f $self->{file};
35 return $self->_pop();
36 }
37  
38 sub _pop
39 {
40 my ($self) = @_;
41 open my $fh, '+<', $self->{file};
42 my ($line, $pos) = _find_last_line( $fh );
43 return unless defined $line;
44  
45 seek( $fh, $pos, 0 );
46 truncate( $fh, $pos );
47 return $line;
48 }
49  
50 sub drop
51 {
52 my ($self, $arg) = @_;
53 return unless -f $self->{file};
54 if( !defined $arg )
55 {
56 $self->_pop();
57 }
58 elsif( lc $arg eq 'all' )
59 {
60 $self->clear()
61 }
62 elsif( $arg =~ /^[0-9]+$/ )
63 {
64 $self->_pop() foreach 1 .. $arg;
65 }
66 return;
67 }
68  
69 sub _find_last_line
70 {
71 my ($fh) = @_;
72 my ( $lastpos, $lastline );
73 while( my ( $line, $pos ) = _readline_pos( $fh ) )
74 {
75 ( $lastpos, $lastline ) = ( $pos, $line );
76 }
77 return unless defined $lastline;
78  
79 chomp $lastline;
80 return ($lastline, $lastpos);
81 }
82  
83 sub _readline_pos
84 {
85 my $fh = shift;
86 my $pos = tell $fh;
87 my $line = <$fh>;
88 return ( $line, $pos ) if defined $line;
89 return;
90 }
91  
92 sub list
93 {
94 my ($self, $ofh) = @_;
95 $ofh ||= \*STDOUT;
96 return unless -f $self->{file};
97  
98 open my $fh, '<', $self->{file};
99 print {$ofh} reverse <$fh>;
100 return;
101 }
102  
103 1;
104  
105 __END__