Perl

Perl

Perl is a highly capable, feature-rich programming language with over 30 years of development.

strict

Pragma to restrict unsafe constructs

use strict;

warnings

Pragma to control optional warnings

use warnings;

Scalars

Declare scalar

my $availableName = "";

Compare strings

if ($availableName eq $lastResult) {
  $continueProcessing = 1;
}

chomp

Remove newlines

chomp $firstname;

Arrays

Read array from STDIN

my @firstnames = <STDIN>;

Copy array (TODO dive into deep copy)

my @lastnames = @firstnames;

Initialize array

my @names = ();

Iterate through an array

foreach $firstname (@firstnames) {
  # Do something
}

Sort an array

@sortednames = sort { $a cmp $b } @names;

Execute a shell command and capture the results into an array

my @results = `nslookup $tryname.com`

Read off the front of an array

my $foundString = shift @results;

Print an array, adding newlines

print "$_\n" for @resortednames;

Regular Expressions (Regex)

Match a value within a string

my $isAvailable = ($foundString =~ m/server can/);

Hashes

Declare a hash

my %resultshash = ();

Assign a hash value

$resultshash{$result} = 1;

File handles

Print to STDERR

print STDERR "$foundString\n";

Open a file in read mode

open(FH, '<', 'data') or die $!;

or

open my $fh, '<', 'data' or die $!;

Open a new file in write mode

open(FH, '>', 'data') or die $!;

or

open my $fh, '>', 'data' or die $!;

Open a new file in append mode

open(FH, '>>', 'data') or die $!;

or

open my $fh, '>>', 'data' or die $!;

Close the file

close(FH);

or

close $fh;

usleep

Sleep in microseconds

use Time::HiRes qw(usleep);

# Sleep for 50 miliseconds
usleep(50000);

See also

Modules

Net::DNS

Examples

cpan

Install cpanminus

brew install cpanminus