perl : find if IP address is in Network range

Using NetAddr::IP one can find if a given IP address is in provided Network range or on the subnet. This can take many different representations of the subnet address. For example you can throw at it the CIDR (e.g. or explicit start and end addresses (e.g. or even with network mask (e.g. mask Following example shows all of these possible cases.


use NetAddr::IP;

my $ipAddr  = "";
my $netAddr = ""; # -

my $network  = NetAddr::IP->new($netAddr);
#my $network  = NetAddr::IP->new("", "");
#my $network  = NetAddr::IP->new("", "29");
#my $network  = NetAddr::IP->new("");
my $ip = NetAddr::IP->new($ipAddr);

if ($ip->within($network)) {
        print $ip->addr() . " is in same subnetn";
else {
        print $ip->addr() . " is outside the subnetn";

There are multiple ways the input for network can be provided (four ways are shown above with 3 commented).

perl : Process Command Line Arguments

GetOpt module in perl provides a very easy way to process the command line arguments. It also performs the type check. Here is a sample snippet that I use very often.

use Getopt::Long;

#Process command line arguments
$result = GetOptions(
	"port=i"	=> $Port,
	"host=s"	=> $Host,
	"interval=f"	=> $Interval,
	"random!"	=> $Randomize,
	"h"		=> $Help

The type after the equal “=” sign dictates the type of variable that is expected. This is very helpful because the module will perform the type checking and ensure that it receives what is expected. For example if you try to give –port “abcd” it will fail that an integer is expected. Read on for a brief explanation of types. Continue reading

perl : Generate Random Data Natively

If you have the luxury to use Data::Random then use that by all means. But if that is not available (for example in production environment), here is another way to create some random data.

sub generate_random_data
	my $passwordsize = shift;
	my @alphanumeric = ('a'..'z', 'A'..'Z', 0..9);
	my $randpassword = join '',
	map $alphanumeric[rand @alphanumeric], 0..$passwordsize;

	return $randpassword;

perl : Extract filename from full path

To extract the name of the file the quick way is to use substr and rindex commands to strip the path from filename as shown below.


my $path='/path/to/search/filename';
my $fname= substr($path, rindex($path,"/")+1, length($path)-rindex($path,"/")-1);
print "$fnamen";

If you have the luxury of using Perl Packages, then use following solution which is very clean.


use File::Basename;
my $path='/path/to/search/filename';
my $fname = basename($path);
print "$fnamen";

perl : Read filenames from a Directory

Perl provides built in glob function which can be used to read the list of files in a directory.

@files = </path/to/search/pattern_to_search>;

Here is working code example that prints all filenames from current directory, one per line. The glob happens when the <> characters pulls the filenames into the @files array.

@files = <*>;
foreach $file (@files) {
        print "$filen";

So if you were to find all php files in your webserver directory use

@files = </var/www/htdocs/*.php>

find broken symlinks

If you have a big project with multiple shared libraries, there is a chance to run into soft links that are no longer pointing anywhere. Here are couple of ways to find those dangling soft links that no longer point to any real file using the Unix find command.

These are in preferred order.

find /path/to/search -type l | (while read FN ; do /usr/bin/test -e "$FN" || echo "$FN"; done)
find /path/to/search -type l ! -exec /usr/bin/test -r {} ; -print
find -L /path/to/search -type l

So here is how these can be used to clean out those dangling soft links (again in preferred order). We use rm to ensure that any aliases don’t kick in. First one is the best way which is portable to most Unix platforms.

find /path/to/search -type l | (while read FN ; do /usr/bin/test -e "$FN" || rm -f "$FN"; done)
find -L /path/to/search -type l -exec rm -f {} ;
find -L /path/to/search -type l -delete

Note: When using in script, make sure to escape the properly.

Interoperability Issues between SunOS and Linux

-delete is not supported on SunOS find. It is available on GNU findutils. So using -exec to invoke rm command would be portable. As well as the test for existence /usr/bin/test -e is portable. Make sure to use /usr/bin/test instead of shell built in test because on sh the flag -e is not available.

Update (2011-08-12) : /usr/bin/test should be used for interoperability.

perl : Set different TimeZone for script

Here is how to set the timezone inside a perl script. A use case is when the application is communicating with some server in a different timezone and you want to log the time in the timezone of the other end instead of the timezone where this script is running.

$ENV{TZ} = ':/usr/share/zoneinfo/US/Eastern';

perl : Create unix time from readable time

Many a times you may need to convert the human readable time into the Unix time. When all the information is passed to “mktime” it returns the unixtime. And to reverse it simply use “localtime”. Here is the example.

use POSIX;
use strict;
use warnings;

my $sec = 6;
my $min = 7;
my $hour = 8;
my $day = 9;
my $mon = 10 - 1;
my $year = 2004 - 1900;
my $wday = 0;
my $yday = 0;

my $unixtime = mktime ($sec, $min, $hour, $day, $mon, $year, $wday, $yday);
print "$unixtimen";

my $readable_time = localtime($unixtime);
print "$readable_timen";

Found at