use strict; sub prepareFormat { my $format = shift(); my ($i, @order) = 0; $format =~ s/([YMDhms]+)(\?)?/ $order[$i++] = substr($1,0,1); '('.('\d' x length($1))."$2)"/ge; $format = qr/^(?:$format)$/; return [$format, \@order]; } sub parseDate { my ($format, $date) = @_; my @data = ($date =~ $format->[0]) or return; my %result; for(my $i = 0; $i <= $#data; $i++) { $result{$format->[1]->[$i]} ||= $data[$i]; } return map $result{$_}, qw(Y M D h m s); } #my $format = prepareFormat ('YYYY/MM/DD'); #my $format = prepareFormat ('YYYY-DD-MM|YYYY-DD-M|YYYY-D-MM|YYYY-D-M'); #my $format = prepareFormat ('YYYY-DD?-MM?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?'); #my $format = prepareFormat ('YYYY-DD?-MM? hh?:mm?(?::ss?)?'); my $format = prepareFormat ('YYYY-DD?-MM?(?: hh?:mm?(?::ss?)?)?'); while (<>) { chomp; my ($year, $month, $day, $hour, $min, $sec) = parseDate($format, $_) or print "\tNot in the right format!\n" and next; print "Year: $year, Month: $month, Day: $day, Hour: $hour, Min: $min, Sec: $sec\n"; }