Splitting YYYYMMDD date into 3 parts in Perl

How do I split a date that has the form YYYYMMDD into its components?

my ($yyyy, $mm, $dd) = $date =~ /(\4d+)(\2d+)(\2d+)/;
+3
source share
5 answers
my ($year, $month, $day) = unpack "A4A2A2", $date;

packand unpackuses invalid built-in functions that can be used for high power.

+14
source
my ($year, $month, $day) = $date =~ /^(\d{4})(\d{2})(\d{2})\z/a
    or die "bad date: $date";
+4
source
#!/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();

, , 2010063011, , 20100630, .

+4

, DateTime. CPAN.

0

, \d Unicode, .

So, if you want to do an input check, use '[0-9]' instead of '\ d'.

-1
source

Source: https://habr.com/ru/post/1752921/


All Articles