On Mon, Dec 13, 2010 at 1:05 AM, John W. Krahn <jwkr...@shaw.ca> wrote: > shawn wilson wrote: >> >> i'm trying to exclude undefined variables for that are to be put into >> a sql database date field, but none of this is working: >> >> sub correctdate { # make valid sql DATE field >> my $date = $_[ 0 ]; >> >> my ($month, $day, $year) = split / /, $date if defined( $date ); > > That may not work correctly: > > perldoc perlsyn > [ SNIP ] > Statement Modifiers > [ SNIP ] > NOTE: The behaviour of a "my" statement modified with a > statement modifier conditional or loop construct > (e.g. "my $x if ...") is undefined. The value of the "my" > variable may be "undef", any previously assigned value, or > possibly anything else. Don't rely on it. Future versions of > perl might do something different from the version of perl you > try it out on. Here be dragons. > > You probably want something like: > > defined $date and my ( $month, $day, $year ) = split /[\s,]+/, $date; > > >> $day =~ s/,//g if defined( $day ); >> >> my %monnum = qw( >> January 01 February 02 March 03 April 04 May 05 >> June 06 July 07 August 08 September 09 October 10 >> November 11 December 12 >> ); >> >> if( $year&& $month&& $day ) { >> my $corrected = "$year-$monnum{$month}-$day"; >> } else { >> my $corrected = "0000-00-00"; >> } > > my() creates a variable that is only visible inside the scope of the {} > braces. You probably want something like: > > my $corrected = $year && $month && $day > ? "$year-$monnum{$month}-$day" > : "0000-00-00"; > >> return $corrected; >> }
the above should work. thanks. > > Or perhaps you could do something like this: > > sub correctdate { # make valid sql DATE field > my $date = $_[ 0 ]; > > my %monnum = qw( > January 1 February 2 March 3 April 4 > May 5 June 6 July 7 August 8 > September 9 October 10 November 11 December 12 > ); > > my ( $month, $day, $year ) = defined $date > ? map( $monnum{ $_ } || $_, split /[\s,]+/, $date ) > : ( 0, 0, 0 ); > > return sprintf '%04d-%02d-%02d', $year, $month, $day; > } > though that might work, it looks a bit complicated - i hate using a ton of $_ - that code was a pain to understand... i'd use it if i didn't have to maintain it :) thanks for your help. i'll use the former first thing tomorrow. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/