http://www.perlmonks.org?node_id=1003818

jonagondos has asked for the wisdom of the Perl Monks concerning the following question:

why is it that when i dont give any user input the else statement isnt executed saying "no user input"? it just tells me circumference is equal to 0

#!/usr/bin/perl $radius_times = 2; $radius_times_2 = 3.141592654; $radius_times_2 *= $radius_times; while (1) { print "enter the radius\n"; $user_radius = <STDIN>; chomp($user_radius); if (defined($user_radius)) { $user_radius *= $radius_times_2; print "circumference is equal to $user_radius\n"; } else { print "no user input"; } }

Replies are listed 'Best First'.
Re: else statement not being executed
by greengaroo (Hermit) on Nov 14, 2012 at 14:34 UTC

    When you "chomp" $user_radius, it is no longer "undef", it becomes an empty string, therefore it is always defined. You should also verify if it is empty.

    Testing never proves the absence of faults, it only shows their presence.
Re: else statement not being executed
by choroba (Cardinal) on Nov 14, 2012 at 14:35 UTC
    Empty string is defined. Check length or even looks_like_number from Scalar::Util.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: else statement not being executed
by flexvault (Monsignor) on Nov 14, 2012 at 14:44 UTC

    Welcome jonagondos,

    The line you need to change is:

    if (defined($user_radius))
    to
    if ( $user_radius )

    '$user_radius' is defined, but equal to "". Even if you undefined it in the loop, you still would define it when you typed the 'CR'

    Good Luck!

    "Well done is better than well said." - Benjamin Franklin

      thanks guys
Re: else statement not being executed (tangential note))
by ww (Archbishop) on Nov 16, 2012 at 14:19 UTC

    For future reference, you may want to give some thought to the way you name variables. For example, the variable name $radius_times_2 (Ln 4) seems to suggest that it should contain a value double that of some radius... but you then define it as $radius_times_2 = 3.141592654; or pi.

    Your first var, $radius_times = 2; (Ln 3) is only a little bit better. The value 2 has no per se relevance to radius; it's merely a multiplier, so why not call it $multiplier?

    By the time you get to $radius_times_2 *= $radius_times (Ln 5), you're waaaaay out in the deep grass. OTOH, something like $pi_times_2 = $pi * $multiplier is far less likely to trip the unwary than a redefinition of $pi. Yes, it's clumsy (there are many reformulations that would improve my offering) and it's less concise, but clarity trumps brevity in most practical cases.

    You can't confuse the computer with that kind of thing, but you sure can make it hard on yourself; some future maintainer, or even the muzzy-brained, early-morning monk who considered offering assistance.