Perl Cheatsheet
Create directory if it doesn’t already exist
my $createDir = "C:\codaxe";
unless(-d $createDir){
mkdir $createDir;
}
For Debug output string representation of variable
use Data::Dumper; print Dumper($foo);
Delete all subdirectories and files from specified path
sub DirectoryDelete {
my $dirtodel = pop;
my $sep = '\\';
opendir(DIR, $dirtodel);
my @files = readdir(DIR);
closedir(DIR);
@files = grep { !/^\.{1,2}/ } @files;
@files = map { $_ = "$dirtodel$sep$_"} @files;
@files = map { (-d $_)?DirectoryDelete($_):unlink($_) } @files;
rmdir($dirtodel);
}
Change current working directory
my $setWorkingDir = "C:\codaxe";
chdir( $setWorkingDir ) or die("Could change working directory to $setWorkingDir");
Get all files in current directory
use File::Find;
use Cwd;
#Array which will contain all of the files in the current directory
my @allFilesCD;
#Extension of files to gather, if you want all use *
my $fileExtension = "txt";
find(sub { if((-f($_)&&$_=~/.*.$fileExtension?$/i)) {
push(@allFilesCD,$File::Find::name);
}
}, cwd());
Get all directories
#for first level down only
my @dirs = grep { -d } glob 'C:\mydata\*';
#for all levels down
find(\&dirs_all, "C:\\mydata\\");
sub dir_names {
print "$File::Find::dir\n" if(-f $File::Find::dir,'/');
}
Get all files with specific keyword in name
my $keywordInFile = "codaxe";
my @returnedFiles = grep {/.*$keywordInFile\.*/i} <*>;
Check if file exists
if(-e "C:\codaxe.txt") {
echo "File Exists";
}
Delete file
my $fileToRemove = "C:\codaxe.txt"; unlink($fileToRemove) or die( "Couldnt not remove $fileToRemove.");
Get entire content of file to scalar variable
my $inputFile = "C:\codaxe.txt";
open(FILE,"$inputFile") or die;
# Fetch all content of current file to scalar allLines
my $allLines = do { local $/; };
Throw Catch Framework
# throw class referenced from http://axkit.org/docs/presentations/tpc2002/exceptions.pdf
sub throw {
my $mess = join('', @_);
$mess =~ s/\n?$/\n/;
my $i = 1;
local $" = "', '";
package DB;
while (my @parts = caller($i++)) {
my $q; $q = "'" if @DB::args;
$mess .= " -> $parts[3](@DB::args)" .
" at $parts[1] line $parts[2]\n";
}
die $mess;
}
# Setup your try catch structure and throw exceptions when needed
eval {
if(defined($ARGV[0])) {
}
else {
throw thrParamMissing;
}
};
# Catch exceptions and execute different instructions based on them
if($@) {
open (ERRORFILE, '>errors.log');
if ($@ =~ thrParamMissing) {
echo thrParamMissing;
}
print ERRORFILE $@;
die $@;
close (ERRORFILE);
}
exit 0;
Read file line by line and remove specific character
my $inFile = "C:\codaxeIN.txt";
my $outFile = "C:\codaxeOUT.txt";
my $INFILE;
my $OUTFILE;
open($INFILE, $inFile) or die("Could not open $inFile");
open($OUTFILE, ">$outFile") or die("Could not open $outFile");
while (<$INFILE>) {
# replace & sign with &
s/\&/\&/g;
print $OUTFILE "$_";
}
close($INFILE);
close($OUTFILE);
Generate Random String
sub generate_random_string
{
# the length of the random string to generate
my $length_of_randomstring=shift;
my @chars=('a'..'z','A'..'Z','0'..'9','_');
my $random_string;
foreach (1..$length_of_randomstring) {
# rand @chars will generate a random
# number between 0 and scalar @chars
$random_string.=$chars[rand @chars];
}
return $random_string;
}
Check if an executable is runnable in perl
# The following allows to run myapp siliently from the terminal but capture the output in $myApp
# You can then do string comparison to check if the app is installed or runnable
my $myApp= `myapp 2>&1`;
if(!($myApp=~ m/getactivewindow/)) {
print "\nERROR: Application not found\n\n";
exit 0;
}
Replace string
$myString=~ s/on/off/; # this replaces "on" with "off" inside $myString
Call a Perl script within another Perl script
#Option 1:
system("/home/myScript.pl ");
#Option 2 (note: these are back ticks not single quotes, this will give you the output from the script):
@myOutput = `/home/myScript.pl`
Send email with attachment
use MIME::Lite; my $emailMsg= MIME::Lite->new( From => 'from@email.com', To => 'to@email.com', Cc => 'to@email.com', Subject => 'Email Suject goes here', Type => 'multipart/mixed', ); $emailMsg->attach( Type => 'TEXT', Data => "Body of messages goes here", ); $emailMsg->attach( Type => 'text/plain', Path => 'filename.txt', Filename => 'filename.txt', ); $emailMsg->send;
Extract filename from path
Embed perl in bat file
Going through XML nodes
Call function through variable
Perform HTTP Request
Get Options
Run EXE
PerlLib
Extract zip to dir
Check error log for compilation errors