I was wondering if anyone had any suggestions on improving the following code (if possible) so that it didn't need the repeated (my @a = $time =~ ...), possibly using case/switch or given/when or some other idea that i'm missing?
my $time = '12:59pm';
if( my @a = $time =~ m/^(\d\d?)(am|pm)$/ ) { tell_time( $a[0], 0, $a[1] ) }
if( my @a = $time =~ m/^(\d\d?):(\d\d)(am|pm)$/ ) { tell_time( @a ) }
if( my @a = $time =~ m/^(\d\d?):(\d\d)$/ ) { tell_time( @a ) }
sub tell_time
{
my $hour = shift;
my $minute = shift || '00';
my $ampm = shift || ( $hour > 12 ) ? 'pm' : 'am';
print "Hour: $hour, Minute: $minute, AMPM: $ampm\n";
}
I've tried playing around with Switch and the 5.10 given/when but can't seem to be able to do something like:
given( $time )
{
when( /^(\d\d?)(am|pm)$/ ) { tell_time( $_[0], 0, $_[1] ) }
when( /^(\d\d?):(\d\d)(am|pm)$/ ) { tell_time( @_ ) }
when( /^(\d\d?):(\d\d)$/ ) { tell_time( @_ ) }
}
That doesn't fly because @_ appears to be storing $time.
also note I'm more interested in the syntax of the problem than the problem the code solves. I'm well aware that I could use Time::ParseDate to figure out the various parts of a string formatted like a time or date.