Perl - setting a variable ?

hi there, I have a question about a snippet of code i have which runs localtime() to convert the current date/time into a mysql happy format

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
printf "%4d-%02d-%02d  %02d:%02d:%02d\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;

If i run the above as a standalone script, i get the desired result

 # ./time.pl 
2009-09-01 10:22:18

However, what i want to do is incorporate it as part of another script and populate an internal variable with the result rather than sending it to standard out ...so i tried this

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
my  $datetime = printf "%4d-%02d-%02d  %02d:%02d:%02d\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;

print "\n datetime equals $datetime\n";
# ./time.pl 
2009-09-01 10:10:31

datetime equals 1
#

but as you can see, not only has it still output to result to standard out (not ideal), but it has populated the variable $datatime with the value "1"

is there something im doing drstically wrong here

any hlp would be great

printf will print the string to a filehandle (STDOUT by default) and return a status code.
sprintf will print nothing, but return the interpolated string, which you then can assign to a variable.
See also: perldoc -f sprintf

wow, thankyou that solves all my problems ....perl really does have an answer for everything doesnt it:b:

script now returns

# ./time.pl 

datetime equals 2009-09-01 11:04:03

---------- Post updated at 07:38 AM ---------- Previous update was at 05:04 AM ----------

just out of interest and to save me repeating this code throughout my script when i need it, is there an easy way to functionise this ?

I tried this

#!/bin/perl -w

sub xxtime() {
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
        my $datetime = sprintf "%4d-%02d-%02d %02d:%02d:%02d\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;
        return $datetime;
}

xxtime();

print "\n time date equals $datetime\n";

but it returns a null value for $datetime

presumably perl has the ability to create functions that

a) i dont pass arguments to
b) return an updated value for a variable that i can use elsewhere in the script

Try it like this:

#!/bin/perl -w

sub xxtime() {
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
        my $datetime = sprintf "%4d-%02d-%02d %02d:%02d:%02d\n",$year+1900,$mon+1,$mday,$hour,$min,$sec;
        return $datetime;
}

my $datetime = xxtime();

print "\n time date equals $datetime\n";

With "my" you create a lexically scoped variable, meaning that variable is only valid within the innermost enclosing block. So the variable $datetime you declare in xxtime() is only valid within this function. To use it outside you have to assign the value return()ed to a new variable.

Thank you very much pludi