Cheating at Perl

Perl code snippet cheat sheet.

Send files to recycle bin:

1
2
use Win32::FileOp qw(Recycle);
Recycle(@ARGV);

Parse out file path:

1
2
3
4
5
use File::Basename;

($name, $path, $suffix) = fileparse($item, '\.[^\.]*');

#where $item is file with fullpath (perhaps derived from path::class

Split at last instance:

1
2
# Splitting at last instance of \
($a,$b) = $line =~ /(.*)\\(.*)/;

Split at first instance:

1
2
# Splitting at first instance of -
($a, $b) = split(/\-/, $line, 2);

Open file for overwriting:

1
open (OUTPUT, ">output.csv");

Open file for append writing:

1
open (OUTPUT, ">>output.csv");

Simple split:

1
($junk, $use) = split (':', $line);

Discard duplicate array entries

1
2
3
use List::MoreUtils qw(uniq);

@uniq_list = uniq(@final);

Simple array sort:

1
@sorted = sort { $a cmp $b } @uniq_list;

Simple directory scan for files:

1
2
3
4
5
6
7
8
9
10
11
use Path::Class;

$dir = dir('\\\\path\\TO\\dir');

while (my $file = $dir->next) {
next if $file->is_dir();
push (@files, $file);
}
foreach $item (@files) {
print $item;
}

Simple file copy:

1
2
3
4
5
6
7
use File::Copy qw(copy);

$a = "path\to\source\file.txt";

$b = "path\to\destination\file.txt";

print <code>copy $a $b</code>;

ODBC SQL Query:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
use DBI;
use DBD::ODBC;

$user="DBUSER";
$auth="DBPASSWORD";
$host="DBSERVER";
$start="DATABASE_NAME";

$dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$start"; $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });
#Example query below - simply lists databases in MS SQL
$sql = qq/SELECT name FROM sys.databases/;
$sth = $dbh->prepare($sql);
$sth->execute();

#Time to manipulate the return
while (@row= $sth->fetchrow_array) {
unshift (@row, $database);
#Print the data
print join("", @row), "\n";
#Push the data into an array
push (@databases, join("", @row), "\n");
}

Remove leading whitepace:

1
$line =~ s/^\s+//;

Remove trailing whitespace:

1
$line =~ s/\s+$//;

Remove leading and trailing whitespace:

1
$line =~ s/^\s*(.*?)\s*$/\1/;

Replace multi whitespace with commas:

1
$line =~ s/\s+/,/g;

Date (including yesterday’s date)

1
2
3
4
5
6
7
8
9
10
11
12
use DateTime;

&time;

sub time {
$logdate = DateTime->now;
$yesterday = DateTime->now->subtract( days =>  1 );
#Today's date:
($date, $time) = split('T', $logdate);
#Yesterday's date:
($date, $time) = split('T', $yesterday);
}

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">