Cheating at Perl
Perl code snippet cheat sheet.
Send files to recycle bin:
1 2 |
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 |
Open file for overwriting:
1 |
Open file for append writing:
1 |
Simple split:
1 |
Discard duplicate array entries
1 2 3 |
Simple array sort:
1 |
Simple directory scan for files:
1 2 3 4 5 6 7 8 9 10 11 |
Simple file copy:
1 2 3 4 5 6 7 |
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 |