Random numbers in Perl

Home > Search
  by

The rand function can be used to print a random number in Perl.

print rand();

 

This will print something like this.

0.948983793121324

 


Set highest possible number

By default, the rand function without any options will print 0 followed by a decimal. Placing an integer inside of the parenthesis will tell the rand function to print an integer that will not exceed the value inside of the parenthesis. For example, if 10 is placed inside of the parenthesis, rand will print an integer somewhere between 0 and 10.

print rand(10);

 

In this example, the non-decimal integer is 7.

7.34484930123189

 

 


Whole number / No decimal

To only print whole numbers with no decimal, use the int override. In this example, a whole number between 0 and 1000 will be printed.

print int(rand(1000));

 

361 was printed.

361

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments