in reply to "natural language" time formatting?
package Seconds2English; use strict; use vars '$AUTOLOAD'; sub new { my ($class, $start_value, %opts) = @_; my $self = bless {}, $class; $self->_build($start_value, \%opts); return $self; } sub _build { my ($self, $start_value, $opt_ref) = @_; $start_value = abs(int($start_value)); return 0 if ($start_value == 0); $self->{'time'} = $start_value; $self->{'mod_hash'} = { 'minute' => 60, 'hour' => 3_600, 'day' => 86_400, 'week' => 604_800, }; if (exists $opt_ref->{'month'} && $opt_ref->{'month'}) { $self->{'mod_hash'}{'month'} = $opt_ref->{'month'}; } else { $self->{'mod_hash'}{'month'} = 2_592_000; } if (exists $opt_ref->{'year'} && $opt_ref->{'year'}) { $self->{'mod_hash'}{'year'} = $opt_ref->{'year'}; } else { $self->{'mod_hash'}{'year'} = 31_536_000; } for my $unit ( qw(year month week day hour minute) ) { if ($start_value % $self->{'mod_hash'}{$unit} != $start_value) + { $self->{$unit} = int($start_value / $self->{'mod_hash'}{$u +nit}); push @{$self->{'units'}}, "$self->{$unit} $unit"; ${$self->{'units'}}[-1] .= 's' if ($self->{$unit} > 1); $start_value = $start_value % $self->{'mod_hash'}{$unit}; } } if ($start_value) { $self->{'second'} = $start_value; push @{$self->{'units'}}, "$self->{'second'} second"; ${$self->{'units'}}[-1] .= 's' if ($start_value > 1); } if (@{$self->{'units'}} > 2) { my $last = pop @{$self->{'units'}}; $self->{'english'} = join ', ', @{$self->{'units'}}, "and $las +t"; } elsif (@{$self->{'units'}} > 1) { $self->{'english'} = "${$self->{'units'}}[0] and ${$self->{'un +its'}}[1]"; } elsif (@{$self->{'units'}} > 0) { $self->{'english'} = "${$self->{'units'}}[0]"; } } sub AUTOLOAD { return if (our $AUTOLOAD =~ /::DESTROY$/); my $self = shift; my ($sub) = $AUTOLOAD =~ /.*::(\w+)$/; if (exists $self->{$sub}) { return $self->{$sub}; } elsif (grep /\b$sub\b/, qw(year month week day hour minute second +english time)) { return 0; } else { die "\n$sub is not valid and the author has done a poor job of + documentation\n"; } } 1; ################################################# # # And then the testscript.pl to see how it works # ################################################# #!/usr/bin/perl -w use strict; use Seconds2English; my $object = Seconds2English->new(1000000); print $object->year(), "\n"; print $object->month(), "\n"; print $object->week(), "\n"; print $object->day(), "\n"; print $object->hour(), "\n"; print $object->minute(), "\n"; print $object->second(), "\n"; print "This is what you were after\n"; print $object->english(), "\n"; print "The original time entered was\n"; print $object->time(), "\n";
Cheers - L~R
Update: If you are interested, I will update this later with POD and give better examples as well as make sure that it works with all kinds of test data - just let me know.
|
---|