#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    Perl date reformat different for file v hard-coded input


    I am trying to change date formats with regex but get cannot get the regex substitution to work when I input a line (and then split into fields). Following is the script that demonstrates the problem (this is my first post so if I am breaking any rules please let me know)...

    #!/usr/bin/perl
    # gr3b.plx
    use warnings;
    use strict;
    my $input;
    my @splitline;
    my $DATE;

    # Task: $splitline[2] date reformat dd/mm/yyyy to yyyy/dd/mm

    # hard-coded input string - works just fine
    $input = "Nurk,Frederick,31/08/1935,205-750-586T,2/10/2012,8:45 am,15mins,8:47 am,8:50 am,Allen,28/08/2012";
    @splitline = split(",", $input);
    $DATE = $splitline[2];

    print "\n\n\t\t----- Example 1: Manually inserted string -----\n";
    print "Input date (manual) is $DATE\n";
    $DATE =~ s/(\d{1,2})\/(\d{1,2})\/(\d{4}).*/$3-$2-$1/;
    print "Output date after reformat is $DATE\n\n\n";


    print "\t\t----- Example 2: CSV input loaded into array -----\n";

    # same string from file - does not reformat
    while (<>) {
    chomp $_;
    @splitline = split(",", $_);
    print "Input date (from file) is $splitline[2]\n";
    $splitline[2] =~ s/(\d{1,2})\/(d{1,2})\/(d{4}).*/$3-$2-$1/;
    print "Output date after reformat is $splitline[2]\n\n\n";
    }

    # Here is the 2 line input file I used (after removing comment hashes)...

    #Nurk,Frederick,31/08/1935,205-750-586T,2/10/2012,8:45 am,15mins,8:47 am,8:50 am,Allen,28/08/2012
    #Poisson,Jeanette,11/04/1938,280-390-300V,2/10/2012,9:00 am,15mins,8:54 am,9:52 am,Allen,26/09/2012
  2. #2
  3. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,221
    Rep Power
    1809
    In your regex, \d{1,2} means one or two digits.

    d{1,2} means the letter d one or two times.

    d{4} means four d's.

    Comments on this post

    • Laurent_R agrees
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,873
    Rep Power
    1225
    Keath correctly points out why your regex was failing.

    Since we're working with Perl, TMTOWTDI (there's more than one way to do it).
    Code:
    $splitline[2] = join '-', reverse split /\//, $splitline[2];

    Comments on this post

    • Laurent_R agrees
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2014
    Posts
    2
    Rep Power
    0

    Keath/Fishmonger - thanks


    Your responses have been very helpful

IMN logo majestic logo threadwatch logo seochat tools logo