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

Dear Monks, I am REALLY new in Perl(btw im new in everything about programming),in fact i've only started to write code 3 or so days ago.And I was wondering if any of you could help me,because I have a piece of code: sub Char{ my $char=400; my $hp= $char - int(rand(20)); print $hp ; } print Char(); The purpose of this (tiny) piece of code is to make a "character" lose hitpoints between numbers 0-20, he is going to start with 400 hitpoints,and lose randomly from 0-20 hitpoints per turn.The problem is idk how to have Perl save that piece of data,so as when it loses for example 20, he will have 380,but then when i print it again it shows 398 for example,instead of 380 - int(rand(20)). Thanks for your answers and helping me

Replies are listed 'Best First'.
Re: How can you save some data?
by ikegami (Patriarch) on Aug 18, 2009 at 21:07 UTC

    [ Please use <p> at the start of every paragraph, and please use <c>...</c> tags around computer text (code, data, output, etc). Your post is barely readable. ]

    Actually, that will make him lose 0-19hp. You need int(rand(21)) to generate an integer in 0-20.

    sub reduce_hp { my ($hp) = @_; $hp -= int(rand(21)); return $hp; } my $char_hp = 400; $char_hp = reduce_hp($char_hp); print("Character now has $char_hp hp\n");
    or maybe
    sub reduce_hp { my ($hp) = @_; $hp -= int(rand(21)); $_[0] = $hp; } my $char_hp = 400; reduce_hp($char_hp); print("Character now has $char_hp hp\n");

    It's a rather useless function, though. It simply shifted code without adding value.

Re: How can you save some data?
by leighsharpe (Monk) on Aug 19, 2009 at 04:15 UTC
    Your mistake in this sub:
    sub Char{ my $char=400; my $hp= $char - int(rand(20)); print $hp ; }
    is that you re-initialise the character's hit points to 400 every time you call it. The first line sets their hit points to 400, and then the next line subtracts a random number from it. Why do you need this in a function at all? Isn't it easier to just do
    $hp= $hp-int(rand(20));
    instead of calling a function?