-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom
executable file
·91 lines (64 loc) · 2.59 KB
/
random
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/perl -CA
use 5.012; # use newer features such as "say"; implies "use strict"
use open qw(:std :utf8); # use UTF-8 for all I/O (by default)
use utf8; # allow UTF-8 in source code
use warnings; # warn if doing silly things
use Scalar::Util 'looks_like_number';
my $result;
if (@ARGV) {
# At least one argument -- check that there are no more than two
die "Too many arguments\n" if @ARGV > 2;
my $first = $ARGV[0];
my $offset = @ARGV > 1 ? $ARGV[1] : 0; # offset may be 2nd argument
my $limit;
if (looks_like_number $first) {
$limit = $first;
} elsif ($first =~ /^(\d+)(?:[–-]|\.\.)(\d+)$/) {
die "Invalid arguments: Don't specify range ($first) AND offset ($offset)\n" if @ARGV > 1;
my $lower = $1;
my $upper = $2;
($lower, $upper) = ($upper, $lower) if $lower > $upper;
$offset = $lower;
$limit = $upper - $lower;
} else {
die "Unexpected argument (not an integer or range): $first\n";
}
$result = int(rand $limit);
$result += $offset;
} else {
# No arguments
$result = rand;
}
say $result;
=head1 NAME
random - return a random number
=head1 SYNOPSIS
random
Returns a random real in the range [0, 1).
random N
Returns a random integer in the range [0, N).
random N OFFSET
Returns a random integer in the range [OFFSET, OFFSET+N).
random LOWER-UPPER
random LOWER–UPPER
random LOWER..UPPER
Returns a random integer in the range [LOWER, UPPER). A hyphen (-), a dash (–),
or two dots (..) may be used as separators. If UPPER is smaller than LOWER, the specified
limits are switched automatically. Note that the lower limit is inclusive, while the upper
one is exclusive.
=head1 PREREQUISITES
Just Perl itself, version 5.12 or later.
=head1 AUTHOR
Christian Siefkes <[email protected]>
=head1 COPYRIGHT
Copyright (c) 2014 Christian Siefkes
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.