iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (34)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

May 15, 2008
Reader Question - Would you host your client's work on your website?
About
 
May 15, 2008
How to Create an Ajax Autocomplete Text Field: Part 6
WebReference.com
 
May 14, 2008
Poll: Are the browser safe colors still needed?
About
 
May 14, 2008
Google Doctype launched
About
 
May 14, 2008
Web Editor Reviews - 6 New Reviews
About
 
May 14, 2008
Build Beautiful Buttons in Photoshop, Part I
SitePoint
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /CGI and Perl

Randomness In Perl 

  Views:    14425
  Votes:    3
by Gyan Kapur 11/27/03 Rating: 

Synopsis:

Perl can be random, too! This article explains how to to use the rand() function in Perl in many contexts, as well as its origins.
Pages: 
The Article

Perl's rand() function is a little bit more interesting than PHP's, because it's behavior isn't as finely tuned to the needs of website programmers, as PHP's.  Furthermore, perl's rand() function is very flexible.

Rand Basics

The rand function returns a decimal number between 0, including 0, and the inputed number, not inclusive.  Therefore, rand(7) would return a decimal between 0 and 7.  If there is no input, then rand would return a number between 0 and 1.

But I Want A Number Between 0 And 50.

print int rand 51;

Perl's rand() function isn't built to give you integers. However, with the int() function you can make it do your bidding.  However, it's important to notice that you have to enter a number one greater than the largest number you're looking for.

Rand And Arrays

my @array = ( 'first possibility','second','third');

print $array[int rand scalar @array];

This code works with almost any input as @array.  URLs, images, possible passwords, whatever you need can be in @array.  The function is returning the int rand result of the scalar value of @array. What's important to note is that with arrays, the scalar value is one higher than the highest key value of @array (Perl's arrays are indexed at 0).

Truly Random

Use of Perl's rand() function is not advised for cryptographers.  The rand() function uses a seed to generate its input, and unfortunately that seed is predictable approximately one third of the time.  Check out perldoc -f srand and perldoc -f rand for more information on this.  Instead, it's advised that for truly random input, one should use the Perl Module Math::TrulyRandom.

Pages: 

Similar/related articles:


 
  Sponsors