I am brand new to Perl, as well as programming, and have been reading the book Beginning Perl by Curtis "Ovid" Poe. I browsed the internet for hours to no avail, so forgive me if this a repost. At the end of Chapter 5 the following excercise is asked:
"You’re writing a game and want to randomly generate a character’s statistics for strength, intelligence, and dexterity. Each statistic is determined by summing the values of two rolls of a six-sided die. For example, if you determine the character’s strength and roll the die twice and get the values 2 and 6, the characters strength is 8 (2 + 6). Write the code to generate a new char- acter. Remember that the code to simulate one roll of a six-sided die is 1 + int(rand(6)) (from Chapter 4). You use a heredoc (see Chapter 3) to print the character’s statistics."
He gives the following code with it :my %stat_for = ( strength => undef, intelligence => undef, dexterity => undef, ); # add your code here print <<”END_CHARACTER”; Strength: $stat_for{strength} Intelligence: $stat_for{intelligence} Dexterity: $stat_for{dexterity} END_CHARACTER
And this is what I came up with:
#!/usr/bin/perl use strict; use warnings; use diagnostics; my %stat_for = ( strength => undef, intelligence => undef, dexterity => undef, ); while ( my ( $stat_name, $randvalue ) = each %stat_for ) { my $randvalue = ( 1 + int(rand(6)) ); my $randv2 = ( 1 + int(rand(6)) ); my $true = $randvalue + $randv2; print <<"END"; Strength: $true\n Intelligence: $true\n Dexterity: $true\n END }
My problem is that this prints 3 times, and I only want it to print once. So I'm looking for the correct way to write this code. Also, this chapter was about if/elsif, for/foreach, while/until, and given/when; And I'm not sure if I should be using them here. I know mine is off of what he laid out, and more than likely horrid. But, it's the best I could come up with, being all new to this. Any help is greatly appreciated.
Thanks in advance!
In reply to New to Perl: Hashes and int(rand()) by Einzig
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |