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

Non-programmer here,
trying to hack a script that prints a variable $X{abc}, but wanting the script to print the variable divided by 20.

Tried simply adding /20 after the variable, but that printed "0".
Also tried defining the desired variable by its formula with $new_abc = $X{abc} / 20, but that also printed "0".

Any help would be very much appreciated.

-reg

Replies are listed 'Best First'.
Re: dividing variables...
by HyperZonk (Friar) on Jul 19, 2001 at 21:55 UTC
    The only reason that $X{abc}/20 would evaluate to zero is if the numeric value of $X{abc} is zero. Three possible reasons:
    • $X{abc} contains a string, that isn't a number ('ab12c' instead of '12').
    • $X{abc} is undef ... that is, it hasn't been defined.
    • $X{abc} == 0
    Check your code for one of these.
      Bingo! Thanks for the fast reply -reg
Re: dividing variables...
by arturo (Vicar) on Jul 19, 2001 at 21:58 UTC

    Your syntax is correct. What's the value in $X{abc}? I suspect that it contains either a 0, is undefined, or is a string. Perl will automagically convert back and forth between strings and numbers as it makes sense in the context, but any string beginning with a non-numerical character1 is going to be interpreted as '0' in a numeric context (such as division).

    1 A -, +, or . followed by digits will make those characters count as 'numeric' for purposes of this test=> e.g. "+1.0" => 1 , "-14" => -14, ".309480" => .309480, and so forth, but "-argh" => 0

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'