Lady_Aleena has asked for the wisdom of the Perl Monks concerning the following question:
Please bear with the as I am a complete novice in programming languages. The only languages that I know are HTML and CSS.
I would like to create a random generator for my website based on several charts, so that the users of my site will not have to manually roll for the results (manually meaning getting out a their dice).
Could someone please help me by showing me a basic generator, such as maybe how to randomly select a color (red, yellow, green, cyan, blue, magenta, white, gray, black)? From there, hopefully, it may be easier for me to understand how this language works.
Any help would be appreciated.
LA
Update
From the tutorials and replies below; here is a sample of some arrays that I have created for randomization.
print "content-type: text/html \n\n"; @AbilityName = qw(strength dexterity constitution intelligence wisdom +charisma ); @Class = qw(Warrior Rogue Priest Wizard Psionisist); @WeapType = qw(bludgeoning piercing slashing missile); @WeapMat = qw(bone metal stone wooden); @NWPlearn = ( "$AbilityName[rand @AbilityName] based", "$Class[rand @Class] specific" ); @Mutation = ( "unable to learn $NWPlearn[rand @NWPlearn] non-weapon proficiencies", "unable to learn $WeapType[rand @WeapType] weapons", "can not use $WeapMat[rand @WeapMat] weapons" ); print "Character mutation: $Mutation[rand @Mutation]", "\n";
This is only the beginning, some parts of the random generator that I would like to create are extremely complex, and these are just a small part of it. I just hope that I got it right so far.
Update 2
Learned a very valuable lesson, the order in which the arrays was listed is important. Also, qw only works on single word items, it doesn't seem to work on phrases. I may be wrong on that, but I will keep researching it. Updated the code above. So far, it works!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Creating a random generator
by dsheroh (Monsignor) on Sep 06, 2007 at 13:55 UTC | |
For the example you've given with colors, the code would be: The first line makes a list of available choices and the second creates a number from 0 to (the number of options - 1), then prints the item at that position in the list. (List elements are numbered starting at 0 rather than 1, so this can produce any element in the list.) | [reply] [d/l] [select] |
by grinder (Bishop) on Sep 06, 2007 at 14:41 UTC | |
Given a number, as in rand(6), it generates an integer which is at least 0 and less than the number it was given (0 to 5 in this case) Almost, but not quite.
This will take the number between 0 and less than 1 and multiply it by 6, nearly always leaving stuff behind the decimal point. If you really don't want the fractional part you have to shave it off with either int($num) or sprintf('%.0f', $num). In the present case it'll work just fine, since Perl will Do The Right Thing and treat the number as an integer anyway, in order to use it as an index into the array. But were the OP to print the number itself, they may be surprised by the result. • another intruder with the mooring in the heart of the Perl | [reply] [d/l] |
|
Re: Creating a random generator
by injunjoel (Priest) on Sep 06, 2007 at 17:48 UTC | |
I think you will find perl to be a great first language to learn. I too pretty much backed my way into consistent programming from an HTML (and JavaScript) background. I am not sure if you mean W3C or the W3schools site but thats not important. The important part is getting some grokable material to foster your nascent perl career. The Beginning Perl Wiki would be my suggestion. As Fletch mentioned, disregarding tone, learning the basics (for-loops, if-elses, etc) first will shallow out the learning curve a great deal. Of course the Monastery is always open. So long as you show what you tried (distilled case, don't just paste every line :), what you found and what you would like to have happen, you will get an answer. So again, Welcome and good luck. -InjunJoel
"I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo
| [reply] |
|
Re: Creating a random generator
by andreas1234567 (Vicar) on Sep 06, 2007 at 13:58 UTC | |
Perl has a built-in random number generator, rand. Follow the link to its documentation.
-- Andreas | [reply] [d/l] |
|
Re: Creating a random generator
by CountZero (Bishop) on Sep 06, 2007 at 15:23 UTC | |
One thing which everyone seems to have forgotten to ask, is: "Are you sure the web-server your program is going to run on has Perl installed?" If not, you are really out-of-luck and will have to look elsewhere for your program. Perl is not something you can just "embed" in your HTML-code and have it magically run and produce the wanted results. CountZero A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James | [reply] |
by Lady_Aleena (Priest) on Sep 07, 2007 at 07:08 UTC | |
CountZero...I am pretty sure that my server has Perl installed since I have forms on my site which have form handlers which I think are written in Perl. The file extensions are .pl. A very long time ago I had to do some weird stuff with those files, which I can't remember now, to make them work. All I remember was that it was weird. | [reply] |
|
Re: Creating a random generator
by Fletch (Bishop) on Sep 06, 2007 at 14:01 UTC | |
To put it bluntly, you don't know any programming languages. HTML and CSS are to programming as knowing how to drive is to building a car from the ground up; yes it's a useful skill and roughly related but verrrrry little knowledge will be of use across the problem domains. Your best bet is to get an introductory book (say Learning Perl from ORA) and absorb that. Then you'll be better equipped to proceed; and you've already got a ready made problem to do your own experimentation. Sure someone could give you a code snippet showing you how to use rand and you could cargo cult that into something that produces some results, but you'll be back again asking how to print it out. Or how to read the list of options from a file. Or . . . ad infinitum. Learn the basics first and you'll save yourself and the people you pester for help much frustration. | [reply] |
by Lady_Aleena (Priest) on Sep 06, 2007 at 14:34 UTC | |
I know that markup and programming languages are very different and have tried to learn the basics from what I have found on the web. I am still looking for a site that has instructions for Perl that is like the HTML and CSS specifications on the W3C site. The best way for me to learn something is to learn how to apply it to my current project. If it would cause to much trouble here, I will try to find somewhere else to get the guidance I will need to complete it. | [reply] |
by ikegami (Patriarch) on Sep 06, 2007 at 15:12 UTC | |
| [reply] |
by Lady_Aleena (Priest) on Sep 07, 2007 at 09:51 UTC | |
by Anonymous Monk on Sep 06, 2007 at 14:41 UTC | |
| [reply] | |
|
Re: Creating a random generator
by dwm042 (Priest) on Sep 06, 2007 at 14:01 UTC | |
Typical output is:
| [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Sep 07, 2007 at 07:46 UTC | |
esper, andreas1234567, and dwm042; There are tiny variations between the code that you gave me. Will that make a difference? I would like to have as little white space as possible. So are all the carriage returns needed between the lines? Now that I have the .pl file, how would I integrate this onto a web page? I do not have Perl installed on my computer at home so the only way to see it working is using on a web page. Update 1 dwm042...On the following line, does "int" mean interger? my $col = int(rand(scalar @colors)); To all Can the items in the array(?) be put on seperate lines? In the actual generator I would like to create each item will be a phrase, a sentence, or a table and most will consist of a lot of html code. Update 2
my @colors = qw(red yellow green cyan blue magenta white gray black); Update 3
| [reply] [d/l] |
by Corion (Patriarch) on Sep 07, 2007 at 08:04 UTC | |
The first step will be to install Perl on your computer. If you have a machine running Microsoft Windows, download and install ActiveState Perl. If you have an Apple computer, chances are good that Perl already is installed. If you have any other brand of computer, the chance that it already has Perl installed isn't that bad either, but ask your machine administrator on how to access it. Then, you can test the .pl files directly by saving them from a text editor and then running them. On Windows, notepad.exe is an ugly but preinstalled editor. Word and Wordpad are unsuitable for editing programs. On the Apple products I don't know what built-in editors there are except vi and vi is an editor you want to avoid when starting out. So, if you have saved your Perl program as myprogram.pl, you can give it a local test run by opening a command prompt in the directory you saved the file to and typing
If there were any errors, Perl will tell you so. If not, look if the output matches what you expect. After that, you can upload the Perl file myprogram.pl to your web account, possibly into the cgi-bin directory, make it executable and then link to that. | [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Sep 07, 2007 at 09:16 UTC | |
by Corion (Patriarch) on Sep 07, 2007 at 09:25 UTC | |
| |
|
Re: Creating a random generator
by elsiddik (Scribe) on Sep 07, 2007 at 12:42 UTC | |
besides this amazing monastery. cheers. | [reply] [d/l] |
by Lady_Aleena (Priest) on Sep 07, 2007 at 19:22 UTC | |
I found another site that could be added... http://www.tizag.com/perlT/index.php | [reply] [d/l] |
by blazar (Canon) on Sep 27, 2007 at 13:04 UTC | |
First of all you may have rendered that url with [http://www.tizag.com/perlT/index.php] or [http://www.tizag.com/perlT/index.php|site], which render respectively like http://www.tizag.com/perlT/index.php and site respectively. Then, having given a peek at that page and reading the very introduction: "This tutorial will be covering the PERL syntax and should provide you with a very solid foundation of PERL for you to build upon. It is recommended that before you start walking through our tutorial that you have a general understanding of Web Development as well as some background knowledge of HTML and CSS as our tutorial is directed toward Web programming." I can tell you in advance that it is definitely a site to be avoided like plague. | [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Sep 27, 2007 at 18:33 UTC | |
by blazar (Canon) on Sep 28, 2007 at 14:48 UTC | |
| |
|
Re: Creating a random generator
by Lady_Aleena (Priest) on Sep 08, 2007 at 06:14 UTC | |
The result I get is... instead of... I tried moving the end quote to before the variables, but that just got me a lot of errors instead. List of errors (condensed):
| [reply] [d/l] [select] |
by wfsp (Abbot) on Sep 08, 2007 at 08:19 UTC | |
| [reply] [d/l] |
by Lady_Aleena (Priest) on Sep 08, 2007 at 08:28 UTC | |
The first 3 scalars are default values. If they are not declared differently in the array, then they don't change. If they are declared in the array, then they change to the new value. Also, all variables have to be as small as possible. I try to conserve space as much as possible, hence the one and two letter variable names. In the array, the name of the monster will be chosen randomly, but the other information such as which book it comes from and what page it is on must be declared, hopefully, within the array. If I have to do separate hashes(?) for each value, it will be way to big. Other random generators with similar variables have up to 10 different variables changed all on one line. Hopefully that made sense. There is a random generation program that I use for what I am trying to recreate in Perl called TableSmith. If you know of it, that will show you where I am coming from. | [reply] |
by wfsp (Abbot) on Sep 08, 2007 at 09:06 UTC | |
by Lady_Aleena (Priest) on Sep 08, 2007 at 11:09 UTC | |
| |
by Lady_Aleena (Priest) on Oct 11, 2007 at 04:06 UTC | |
I was so excited, I found out about exists so I was going to apply it here. Now I can't figure out how to use it, or even if it will work with this.
First, the item from the hash needs to be randomly selected. Then if the variable b is in the key's hash, then print nothing. If the variable b is not in the hash, print ' beholder'. Then if either bk or pg is in the key's hash, then print ' (' and check the following. If bk is in the hash, print it's value. If bk is not in the hash, print 'Monstrous Manual'. If pg is in the hash, print ', page ' and it's value. If pg is not in the hash, print nothing. After those two are done, print a final ')'. If neither bk nor pg are in the key's hash, then print nothing after the key. | [reply] [d/l] [select] |
by graff (Chancellor) on Oct 15, 2007 at 08:07 UTC | |
I was so excited, I found out about exists so I was going to apply it here. Now I can't figure out how to use it, or even if it will work with this. Your problem is not with "exists()" per-se. At the surface, your problem involves punctuation that is incomplete or incorrect, along with insufficient use of parens, when trying to glom together all the steps of your algorithm into a single concatenated string for a "print". Slow down. Also, you are getting mixed up about how your data structure is organized. You initialize %Data{gen} with square brackets, which creates a reference to an anonymous array, and the "random" function is set up to get an array ref from this hash element -- that part of the code says "%Data is a HoA structure". But the elements of data being assigned to %Data{gen} are laid out as a hash, with the value of each element being another hash, which says "%Data is a HoHoH structure" (e.g. $Data{gen}{beholder}{pg} == 21). If you want HoHoH, the initialization would use curlies instead of square brackets: And you would need a different kind of "random()" function in order to select one of those sub-keys ("beholder, "death kiss", etc) at random -- maybe something like: So the first thing to do is decide what sort of data structure you really want, and stick with that. But let's look at the overall task in terms of the way you describe your algorithm: First, the item from the hash needs to be randomly selected.
Then if the variable b is in the key's hash, then print nothing. If the variable b is not in the hash, print ' beholder'.
Then if either bk or pg is in the key's hash, then print ' (' and check the following. That's a bit of tough going, and your sample data doesn't seem to exercise all the contingencies. Still, let's see if I can rephrase it without damaging the intent: If either "bk" or "pg" exists in the key's hash, add a parenthesized string containing a book name, with or without a page number; for a "pg" with no "bk", the default book name is "Monstrous Manual": The rules for use of brackets (square and/or curly) when working with data structures require careful attention to detail, and a clear understanding of what your particular data structure is. Data::Dumper can help with that, but you need to need to start with a structure that makes sense to you, and organizes the data nicely for the things you need to do with it. When in doubt, go back to perlreftut, perlref and perldsc (Data Structures Cookbook) -- I've done that quite often, and it helps. (This thread is getting rather long in the tooth (and just long)... if you continue hitting walls with this pursuit, you might consider focusing on some relatively self-contained issue that is causing trouble, isolate it as a stand-alone problem, and post it as a new thread.) | [reply] [d/l] [select] |
|
Re: Creating a random generator
by Lady_Aleena (Priest) on Oct 01, 2007 at 05:41 UTC | |
Here is an update to what I posted previously in this thread. With all the changes made, this is hopefully more understandable. Because of the length of the script, I have broken it down into several code blocks. Notes are at the end on areas where work still needs to be done. Comments from within the code will be pointing to those notes. Read more... (27 kB)
Lady Aleena
| [reply] [d/l] [select] |
by graff (Chancellor) on Oct 01, 2007 at 13:24 UTC | |
You'll probably want to tweak that to suite your tastes for notations and additional flexibility (and I haven't tried testing it, so it may need some fixing as well). There is one likely (possibly vexing) downside to this approach: the sequence in which %game_data elements are initialized (replacement values put in as needed) will matter, e.g. if a key/array "foo" depends on values from key/array "bar", which depends on values from "glub", etc. If "foo" elements get processed first, they will contain "unprocessed" strings from the "bar" list. To get around that, the data file would need to be ordered according to "primitive sets first", "first-order dependencies next", etc, so that any line with "template symbol" references to arrays is guaranteed to come after the arrays that it references. In that case, you'll need to move the logic for parsing and replacement of values into the "while" loop that reads the file. The for ( keys %game_data ) loop that I suggested above would do them in random order, which would probably do the wrong thing. | [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Oct 03, 2007 at 17:25 UTC | |
An HoA would probably add a bit more confusion right now, though I don't really know. I will look into a plain text file. That large bit of code is confusing, could you possibly break it down for me? I know there is a hash in there somewhere, but not where. Lady Aleena
"An it harm none, do as ye will." | [reply] |
by Lady_Aleena (Priest) on Oct 09, 2007 at 21:21 UTC | |
graff; Every time I look at this I am loving it more, but just for the static data. Since the dynamic data might only be used here, let's not transfer them to the text file right now. That is one headache we don't need. The first section of the code you gave me seems a bit straight forward. I altered it to fit the current naming scheme for the HoA.
Since we are not moving any dynamic content over, is the second bit of code necessary? Now, the third section is the one that could get me into real trouble. I removed a lot of the spacing, but still indented a bit here and there, I hope you don't mind. I changed all that I could find to the current setup as well.
Now, what will get me into the most trouble is all of the regular expressions used. At least that is what I think all of those strings of punctuation are. I rarely use them in the find/replace in my text editor. When I do use them, it is with extreme caution. I will read up on them, but the docs are hard going for me. If you could explain a few of them in the code above, that would help me get a much better grasp on them. Leaving the dynamic portions of the script in it, there shouldn't be any problems with dependency as far as I can tell. Lady Aleena
"An it harm none, do as ye will." | [reply] [d/l] [select] |
by graff (Chancellor) on Oct 10, 2007 at 05:54 UTC | |
by shmem (Chancellor) on Oct 03, 2007 at 17:11 UTC | |
You have to add a bit of magic to your arrays with tie.
Now convert all your array elements which are dynamically constructed (i.e via concatenation of some strings and calls to e.g. random()) into anonymous subs, and tie those arrays:
Do this with every array which has randomly constructed items. Then
will yield e.g.
Solving the static radius problem is left as an exercise to the reader. --shmem
| [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Oct 05, 2007 at 07:08 UTC | |
| [reply] | |
by Lady_Aleena (Priest) on Oct 08, 2007 at 10:23 UTC | |
Addendum to Re: Creating a random generator There are several scripts that will go along with the main Mutation script. These scripts will be part of this random generator and will also need to be independent of it. The scripts below will become part of this ever increasing randomness. I am not sure how I am going to go about getting these to work within the main body of the script. Lady Aleena
"An it harm none, do as ye will." | [reply] |
|
Re: Creating a random generator
by UnstoppableDrew (Sexton) on Oct 04, 2007 at 17:59 UTC | |
| [reply] |
by Lady_Aleena (Priest) on Oct 05, 2007 at 07:29 UTC | |
I have looked into an gotten installed HTML::Template, which may do the same thing as Template::Toolkit. I still don't know how to make or use databases just yet, but I am going to get to it very soon, since I will more than likely need it before this is all over. I do not have MySQL and a lot of other things that everyone recommends on my server. I am already using use CGI in my scripts. I am learning Perl by using it to do those projects. It is the best way for me to learn, since the subject matter holds my interest more than print "Hello World!\n\n"; amongst other things. I build scripts to have them torn down by my betters and shown what I did poorly or wrong. I am glad that there are people here who understand that some of us can't learn from the abstract, we need to put into a familiar subject right away to learn. Thanks for dropping me a line. Lady Aleena
"An it harm none, do as ye will." | [reply] [d/l] [select] |
by UnstoppableDrew (Sexton) on Oct 07, 2007 at 03:04 UTC | |
I scraped your a-c table and turned it into a text file delimited by pipe chars (since there are commas in the data): I wrote a script to stuff the data into the db: That was probably not the most efficient way to do it, but my dbi book is at work and all this is off the top of my head. Script to read the database and dump data into template toolkit template: Template toolkit template to display the data: Live script can be run by hitting this url: http://marold.org/cgi-bin/showtable.cgi | [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Oct 07, 2007 at 19:03 UTC | |
by UnstoppableDrew (Sexton) on Oct 07, 2007 at 18:40 UTC | |
| [reply] |
by Lady_Aleena (Priest) on Oct 07, 2007 at 19:05 UTC | |
by Your Mother (Archbishop) on Jun 27, 2019 at 21:43 UTC | |
|
Re: Creating a random generator
by Lady_Aleena (Priest) on Sep 25, 2007 at 18:53 UTC | |
Read more... (20 kB)
Update 1: Some of the smaller syntax errors fixed.
Update 2: Some of the arrays have been altered. | [reply] [d/l] |
by Limbic~Region (Chancellor) on Sep 26, 2007 at 00:21 UTC | |
Here is some advice on your code. In addition, I recommend reading the advice I gave at Re: Refactoring a large script. Read more... (6 kB)
I believe this is more than enough to chew on for now. Cheers - L~R | [reply] [d/l] [select] |
by Lady_Aleena (Priest) on Sep 26, 2007 at 03:27 UTC | |
Thank you for the fabulous breakdown of issues you see. Let me see if I understand them. The first item is that you suggested that I add -T to the shebang line. I was already told to add -w (after reading perlrun, I may possibly go to -W instead). Can both be added to the shebang? Do the following two items duplicate the same thing? If they do, I would choose to keep the first.
I now only have the following in my code...
@Dice2 became redundant. You expressed concern for my variable names, with the example being @Radius and $radius. I have been using the capitalized version for the array in the original TableSmith version, and the lowercase version for the phrase fragment for a while now. I can tell the difference. All of the data in the script is static. As far as I know the arrays will only change if I think of something to add to them and write it into the code manually. The only thing that will change is the amount of times the user wants to run the script and the amount of times each random element will be called. The script as it is now is only a fragment of what is yet to come. I have a lot of markup to add to make this into a web page. I also have several other sub scripts to write that will be used by this one (but each of those must stand alone as well). The original way I wrote the array dealing with the colors was... I thought that this would save me a few bytes... But you think a hash is better? How would you make that randomly selected and inserted into the following? As soon as I get the entire script working, I will be getting rid of all unnecessary whitespace from it. I just hope that this doesn't go above the amount of bytes I have alloted for it. | [reply] [d/l] [select] |
by Limbic~Region (Chancellor) on Sep 26, 2007 at 15:02 UTC | |
by Anno (Deacon) on Sep 25, 2007 at 20:27 UTC | |
Anywhere you see (AorAn) is where I hope the perl has a nice little way of looking at the first character of the following word and adding "a" or "an". If you don't expect too much, this substitution should do that. It changes th word "a" to "an" if the following word begins with a vowel character. It doesn't deal with "a unicorn" or "an hour" and other vagaries of pronunciation. As to your code, there's a lot of it and I haven't looked at every line by far. One thing that stands out is that there is little separation of code and data. You have a lot of global hashes and arrays, and later ones seem to rely on earlier ones in uncomfortable ways. Ultimately, these would belong in a single (or a few) configurable hashes, with the configuration data in an external file. Otherwise, your code has a massive amount of syntax errors, too many to correct on the fly. It will be nearly impossible to debug remotely, relying only on fatalsToBrowser. You must find a way to run your script locally from a shell so that you can eliminate syntax errors before commiting it to a web server (even a local web server), or indeed, for discussion among perl monks. Anno | [reply] [d/l] [select] |
by ysth (Canon) on Sep 25, 2007 at 22:12 UTC | |
Anywhere you see (AorAn) is where I hope the perl has a nice little way of looking at the first character of the following word and adding "a" or "an".Lingua::EN::Inflect | [reply] |