Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

concating problem

by doubtingben (Novice)
on Apr 21, 2003 at 17:11 UTC ( #252054=perlquestion: print w/ replies, xml ) Need Help??
doubtingben has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am at my wits end here. I am trying to change a date format from month/day/year to year-month-day. Easy right? This works as expected:
#!/usr/bin/perl use strict; my $string = "9/1/2001"; my ($month, $day, $year) = split('/', $string); my $new_date = join('-', $year, $month, $day); print "$new_date\n";
but this doesn't :
... my $string = $line[11]; my ($month, $day, $year) = split('/', $string); my $new_date = join('-', $year, $month, $day); ...
$new_date becomes: "-month-day". I tried:
$new_date = $year.'-'.$month.'-'.$day;

But I get the same result. After some experimentation, it seems the month is starting at the beginning of the string, and overwriting everything after it. During debugging, I see the split works fine, I just can't seem to put it back together correctly.


Can anyone enlighten me?

Thanks.

The worst feeling?
Realizing what you thought was true, is not.

Comment on concating problem
Select or Download Code
Re: concating problem
by krujos (Curate) on Apr 21, 2003 at 17:16 UTC
    Have you checked that $line[11] really contains the date? It looks like your missing the year field (i.e. the string contains month/day).
    update: fixed formatting
Re: concating problem
by Thelonius (Priest) on Apr 21, 2003 at 17:26 UTC
    chomp($string);
    Update: I really should add that if the string contains just a '\r' (and it looks like it might), chomp won't actually work. You'll have to $string =~ s/\r//g; or $string =~ tr/\r//d;
      Thanks, $string =~ s/\r//g; worked. I did already have a chomp in there, with this addition, life makes sense again.
Re: concating problem
by Mr. Muskrat (Abbot) on Apr 21, 2003 at 18:18 UTC

    gbarr has given us Date::Parse so that we do not need to do this sort of thing (splitting dates that is). (Date::Manip would work too but it's a bit big for such a simple project.)

    #!/usr/bin/perl use strict; use Date::Parse; my $string = "9/1/2001"; my ($day,$month,$year) = (strptime($string))[3..5]; $month++; $year+=1900; my $new_date = join('-', $year, $month, $day); print $new_date,$/;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://252054]
Approved by krujos
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (11)
As of 2014-12-27 16:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls