Generate random number in Perl
Answer:
To generate a random number in Perl, e.g. 10 to 20 (inclusive)
my $max = 10;
my $min = 10;
my $random = int( rand( $max-$min +1 ) ) + $min;
Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.
Generate random number in Perl
Answer:
To generate a random number in Perl, e.g. 10 to 20 (inclusive)
my $max = 10;
my $min = 10;
my $random = int( rand( $max-$min +1 ) ) + $min;
How to prevent PHP script from running in Apache
Answer:
If you have a PHP script and want it run under in command line only, not in the web server context, you can use the following method.
<?php
if ( php_sapi_name() != "cli" ) {
print "This script must be run from the command line\n";
exit();
}
Sum of every lines' value in a file
Answer:
Assume you have a file num.txt
1
2
3
4
5
How do you calculate the sum of every lines' value in a file?
Use Perl!
# perl -lne '$x += $_; END { print $x; }' < num.txt
15
Benchmark Perl subroutines
Answer:
The Benchmark module provide a very easy way to compare (cmpthese) the performance of Perl's subroutines.
E.g. The following codes compare the performance of MD5 and SHA1 hashing methods.
#!/usr/local/bin/perl
use strict;
use Benchmark qw(cmpthese);
use Digest::MD5 qw(md5_hex);
use Digest::SHA1 qw(sha1_hex);
my $str = '83b0c3d63e8a11eb6e40077030b59e95bfe31ffa';
my $s;
cmpthese( 1_000_000, {
'md5' => sub{ $s = md5_hex($str) },
'sha1' => sub{ $s = sha1_hex($str) }
});
It will output
# perl compare_md5_sha1.pl
Rate sha1 md5
sha1 934579/s -- -39%
md5 1538462/s 65% --
Obviously, MD5 is faster than SHA1.
How to execute a command repeatedly using bash
Answer:
The following simple bash script will run the echo command, sleep 10 seconds repeatedly.
#!/bin/bash
while [1];
do
echo "Hello!";
sleep 10;
done