Operating System - Linux
1753767 Members
5665 Online
108799 Solutions
New Discussion юеВ

Re: manipulate string with perl

 
SOLVED
Go to solution
steven Burgess_2
Honored Contributor

manipulate string with perl

Hi,

I have a date

my $date = 200609061700;

That I need to look like

2006-09-06 17:00

At the moment I have got as far as

my @date=split(//, $date);

my $newdate = "@date[0,1,2,3]-@date[4,5]-@date[6,7] @date[8,9]:@date[10,11]";

$newdate =~ s/\s//g;

Which gives

2006-09-0617:00

Any help appreciated

TIA

Steve
take your time and think things through
8 REPLIES 8
H.Merijn Brand (procura
Honored Contributor

Re: manipulate string with perl

my ($y,$m, $d, $H, $M) = unpack "A4A2A2 A2A2", $date;

You can also look at modules Date::Calc, and Date::Manip

http://search.cpan.org/search?query=Date%3A%3A&mode=all

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
H.Merijn Brand (procura
Honored Contributor

Re: manipulate string with perl

and the output then

my $newdate = "$y-$m-$d $H:$M";

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
steven Burgess_2
Honored Contributor

Re: manipulate string with perl

Hi

Sorry, I have obtained the date from a file name. I need to insert that date into my database in the format that it expects for the column

Thanks

Steve
take your time and think things through
Marvin Strong
Honored Contributor

Re: manipulate string with perl

Maybe not the best solution.

#!/usr/bin/perl

$date=200609061700;

$year=substr $date, 0, 4;
$mnth=substr $date, 4, 2;
$day=substr $date, 6, 2;
$time=substr $date, 8, 5;

my $newdate = "$year-$mnth-$day $time\n";

print $newdate;
steven Burgess_2
Honored Contributor

Re: manipulate string with perl

Hi

I was also looking a substr but could only work out from the examples how to insert one character.

TIA

Steve
take your time and think things through
H.Merijn Brand (procura
Honored Contributor
Solution

Re: manipulate string with perl

TIMTOWTDI:

my $newdate = sprintf "%04d-%02d-%02d %02d:%02d", unpack "A4A2A2 A2A2", $date;

# perldoc -f pack
# man perlpacktut
# man perlfunc

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Marvin Strong
Honored Contributor

Re: manipulate string with perl

opps I missed that you need a : between hour and min. You could just add two more substr for hour and min, then combine with mine.

of course the unpack is a better solution than mine. I'm going to have dig into unpack more one of these days.

steven Burgess_2
Honored Contributor

Re: manipulate string with perl

Thanks again

Steve
take your time and think things through