Saturday, August 20, 2011

How to Initialize or Clear an Array in Perl



Method 1: Assign an Empty List (Recommended)

The simplest and most highly recommended approach is to reassign the array to an empty list
my @array = ();


Method 2: Modify the Last Element's Index

In Perl, $#array represents the index of the last element in the array. Because Perl arrays are zero-indexed, this value is always one less than the array's total length.

You can manually change the length of the array by assigning a new value to $#array. By setting this index to -1, you destroy all existing values and completely clear the array.
$#array = -1;

Thursday, August 4, 2011

How to shuffle the values in a hash?

use List::Util qw(shuffle);

%hash = (this => 0,
is => 1,
a => 2,
test => 3);

my @values = shuffle(values %hash);
map { $hash{$_} = shift(@values) } (keys %hash);

print "$_\t$hash{$_}\n" foreach keys %hash;

How to Validate an IPv4 Address in Perl Using Regular Expressions

Validating IP Addresses in Perl

When checking if a string is a valid IPv4 address (where each of the four octets must be between 0 and 255), you have two primary approaches in Perl: combining a simple regex with numeric condition checks, or using one complex regex that handles the numeric limits natively.

Method 1: Simple Regex with Numeric Range Checks
This method extracts the four numbers using capture groups (\d+) and then uses a standard if statement to ensure each number falls within the valid 0-255 range. This is often much easier to read and maintain.

Perl
$ip =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/;

if ($1 >= 0 && $1 <= 255 && 
    $2 >= 0 && $2 <= 255 && 
    $3 >= 0 && $3 <= 255 && 
    $4 >= 0 && $4 <= 255) 
{
    # Valid IP Address
}

Method 2: Pure Regular Expression (No If-Statement)
This method uses a more complex regular expression to ensure the numbers match the 0-255 range directly within the pattern match itself. It checks for numbers starting with 2[0-5][0-5] (200-255) or 1?[0-9]?[0-9] (0-199).
Perl
# Validates the IP range directly in the regex match
$ip =~ /\b((2[0-5][0-5]\.)|(1?[0-9]?[0-9]\.)){3}((2[0-5][0-5])|(1?[0-9]?[0-9]))\b/;