Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: saving a random number while generating a new one

by Sinistral (Prior)
on Mar 30, 2011 at 14:38 UTC ( #896430=note: print w/replies, xml ) Need Help??

in reply to saving a random number while generating a new one

What you're encountering is a fundamental misunderstanding of how CGI scripts work. When your user is interacting with your HTML page and CGI script, here's what's happening:

  1. User's browser requests index.html, receives the HTML, and renders it on their local computer
  2. User clicks the roll the dice link, which sends another request for dice.cgi
  3. The web server receives the request for dice.cgi, knows that it is a script, and runs Perl to produce the output
  4. The web server collects the output from your script (the print in your Perl code) and sends it out the network connection to the user's browser
  5. The user's browser receives the HTML output by your Perl code and renders that

Note that your script is running again and again as if it had never run before. It has no state, and the code you've shown has no way of retaining state. As you mention, you can use a file to save previous runs. As an alternative, what you might do is to use CGI::Session to have a session for the user that retains all the runs that they've made. If you don't want something that heavy, then you could use DBI along with DBD::SQLite to have a SQLite database (which is a flat file, ultimately) for your data storage. If you don't want DBD::SQLite, you could use a full blown database engine such as DBD::mysql or DBD::Pg.

Based on your code, it seems that you are not yet familiar with HTML/CGI idioms or syntax, so I would actually pursue a simple text file (Perl excels at reading and parsing simple text files) as your data collection mechanism

  • Comment on Re: saving a random number while generating a new one

Replies are listed 'Best First'.
Re^2: saving a random number while generating a new one
by raybies (Chaplain) on Mar 30, 2011 at 15:13 UTC
    Good responses, and since it hasn't been mentioned and (though it's a pain) you can also pass state data along using "hidden" parameters (if you've got a form/submit), and/or using cookies. Of course there are security issues with some of these approaches.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://896430]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2018-06-21 19:13 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.