How do I split a date that is of the form YYYYMMDD into its constituents?
my ($yyyy, $mm, $dd) = $date =~ /(\4d+)(\2d+)(\2d+)/;
How do I split a date that is of the form YYYYMMDD into its constituents?
my ($yyyy, $mm, $dd) = $date =~ /(\4d+)(\2d+)(\2d+)/;
my ($year, $month, $day) = $date =~ /^(\d{4})(\d{2})(\d{2})\z/
or die "bad date: $date";
#!/usr/bin/perl -w
use strict;
sub main{
my $date = "some text with the numbers 2010063011 and more text";
print "Input Date: $date\n";
my ($year, $month, $day) = $date =~ /\b(\d{4})(\d{2})(\d{2})\b/;
print qq{
Date: $date
Year: $year
Month: $month
Day: $day\n} if (defined $year && defined $month && defined $day);
}
main();
notice this will look for the first date in the regex, it won't work with 2010063011
because it's not a date, but it will work with 20100630
, which is what you want.
my ($year, $month, $day) = unpack "A4A2A2", $date;
pack
and unpack
are underused builtins that can be used to great power.
Note that \d matches any Unicode digits, not just latin decimal digits.
So if you want to do input validation use '[0-9]' instead of '\d'.
Whenever I need to work with dates I use the DateTime module. You can grab it from CPAN.