Home / Programming /
This is a collection of Perl snippets I've written or otherwise come across that I would like available for future reference.
sub showFileContents {
my $file = $_[0];
open FILE, "<$file";
my @hold = <FILE>;
foreach(@hold) {
print $_;
}
close FILE;
}
sub printHeader {
my $header = $_[0];
runOnSystem("clear");
print "\n\n\t$header:\n\n";
}
sub runOnSystem {
my $command = $_[0];
my $debug = $_[1];
if ($debug) {
print "debug: $command\n";
} else {
print "\n\n[[executing: $command]]\n\n";
system("$command");
}
}
sub enterToContinue {
print "\nPress enter to continue...\n";
my $enter = <STDIN>;
}
sub checkYn {
my $prompt = $_[0] . " [Y/n]:";
print "$prompt";
my $rVal = -1;
while($rVal == -1) {
chomp(my $yn = <STDIN>);
if ($yn =~ /^y*$/i) {
$rVal = 1;
} elsif ($yn =~ /^n+$/i) {
$rVal = 0;
} else {
print "Sorry, that's not valid input. Please try again:\n\n$prompt";
}
}
return $rVal;
}
sub checkyN {
my $prompt = $_[0] . " [y/N]:";
print "$prompt";
my $rVal = -1;
while($rVal == -1) {
chomp(my $yn = <STDIN>);
if ($yn =~ /^y+$/i) {
$rVal = 1;
} elsif ($yn =~ /^n*$/i) {
$rVal = 0;
} else {
print "Sorry, that's not valid input. Please try again:\n\n$prompt";
}
}
return $rVal;
}
sub userInput {
my $prompt = $_[0] . ":";
print "$prompt";
my $rVal;
while(!defined $rVal) {
chomp(my $userTyped = <STDIN>);
$rVal = sanitizeUserInput($userTyped);
if (!defined $rVal) {
print "Sorry, that's not valid input. Please try again:\n\n$prompt";
}
}
return $rVal;
}
sub sanitizeUserInput {
my ($userTyped) = @_;
## process $userTyped here - return undef if new input is required;
chomp($userTyped);
if ((length $userTyped) == 0) {
undef $userTyped;
}
return $userTyped;
}
sub getExecutableDirectory {
## requires use Cwd 'abs_path';
my $fullPath = abs_path($0);
my $dirname = dirname($fullPath);
return $dirname;
}
sub getTimeStampString() {
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon += 1;
$mon = sprintf("%02d", $mon);
$mday = sprintf("%02d", $mday);
$hour = sprintf("%02d", $hour);
$min = sprintf("%02d", $min);
$string = "$year$mon$mday-$hour$min";
return $string;
}
this one is a bit more specific, but should be easily adaptable
sub processArguments {
$ranSomething = 0;
for (my $i = 0; $i < scalar(@ARGV); $i++) {
my $arg = $ARGV[$i];
if ($arg =~ /^-(\w)/) {
$arg = $1;
processArgument($arg, $ARGV[$i + 1]);
}
}
if ($ranSomething == 0) {
print "Usage: example usage\n";
}
}
sub processArgument {
my $arg = $_[0];
my $nextArg = $_[1];
if ($arg eq "c" && $nextArg ne "") { #maybe do -e
# most of these are examples as to how to use this code
# my $confFile = $nextArg;
# loadConfFile($confFile);
} elsif ($arg eq "d") {
#$debug = 1;
}
}
sub checkTrailingSlash {
my $str = $_[0];
if ($str !~ /\/$/) {
$str .= "/";
}
return $str;
}
this document last modified: February 03 2018 16:50
Home / Programming /