blib/lib/Time/Sequence.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 8 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 101 CC 5 SCAR 18.9
CC
5
Cov
0%
cut_time
12.0
get_time
6.0
seq_times
6.0
CRAP 6.6
1 #ABSTRACT: simple time sequence base on Date::Calc
2 package Time::Sequence;
3  
4 require Exporter;
5 @ISA = qw(Exporter);
6 @EXPORT = qw( get_time seq_times cut_time );
7  
8 our $VERSION = 0.01;
9  
10 use Date::Calc qw/Mktime Add_Delta_YMDHMS Localtime/;
11  
12 our $TIME_FORMAT = "%04d-%02d-%02d %02d:%02d:%02d";
13 our $DAY_FORMAT = "%04d-%02d-%02d";
14 our @TIME_FIELDS = qw/year month day hour minute second/;
15  
16 sub get_time {
17 my ( $time, %opt ) = @_;
18 $opt{format} ||= $TIME_FORMAT;
19 $opt{delta} ||= {};
20 $opt{delta}{$_} ||= 0 for @TIME_FIELDS;
21  
22 my @s = $time ? parse_time($time) : ( Localtime() )[ 0 .. 5 ];
23 @s = Add_Delta_YMDHMS( @s, @{ $opt{delta} }{@TIME_FIELDS} );
24  
25 return sprintf( $opt{format}, @s );
26 }
27  
28 sub parse_time {
29 my ($t) = @_;
30 $t =~ s/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/$1-$2-$3 $4:$5:$6/;
31 my @times = $t =~ /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
32 return @times;
33 }
34  
35 sub seq_times {
36 my ( $from, $to, %opt ) = @_;
37 $opt{format} ||= $DAY_FORMAT;
38 $opt{delta} ||= { day => 1 };
39 $to ||= get_time();
40  
41 my @s = parse_time($from);
42 my @e = parse_time($to);
43  
44 my @times;
45 while (Mktime(@s)<Mktime(@e) ) {
46 push @times, sprintf( $opt{format}, @s );
47 @s = Add_Delta_YMDHMS( @s, @{ $opt{delta} }{@TIME_FIELDS} );
48 }
49  
50 my $ss = sprintf( $opt{format}, @s );
51 my $ee = sprintf( $opt{format}, @e );
52 push @times, $ee unless ( $opt{trim_end} and ( $ss cmp $ee ) );
53  
54 return \@times;
55 }
56  
57 sub cut_time {
58 my ( $time, $seq_times ) = @_;
59  
60 for ( my $i = 0 ; $i < $#$seq_times ; $i++ ) {
61 my ( $f, $e ) = @{$seq_times}[ $i, $i + 1 ];
62 next if( ($e cmp $time) == -1);
63 last if( ($f cmp $time) == 1);
64 return $f;
65 }
66 return '';
67 }
68  
69 1;