Saturday, July 9, 2011

How to Parse File Paths in Perl Using File::Basename

Using the File::Basename Module in Perl

The File::Basename module provides a simple way to parse file paths into their core components: the directory, the file's base name, and the file extension.

Code Example:

use File::Basename;

# Extract all components at once
my ($name, $path, $suffix) = fileparse($fullname, @suffixlist);

# Extract just the filename (with or without a specific suffix)
my $name = fileparse($fullname, @suffixlist);

# Get just the base filename (equivalent to the Unix 'basename' command)
my $basename = basename($fullname, @suffixlist);

# Get just the directory path (equivalent to the Unix 'dirname' command)
my $dirname = dirname($fullname);

various method of array size in perl -- array length

#----------------------------#
# create a simple Perl array #
#----------------------------#
@foods = qw(burgers fries shakes);

#-------------------------------------------------#
# three different ways to get the Perl array size #
#-------------------------------------------------#

# 1) perl array size with implicit scalar conversion:
$size1 = @foods;

# 2) perl array size with explicit scalar conversion:
$size2 = scalar @foods;

# 3) perl array size with using the index of the last
#    element in the array, plus one:
$size3 = $#foods + 1;

# print the array sizes
printf("The sizes are %d, %d, and %d\n", $size1, $size2, $size3);

Perl DBI examples for DBD::mysql

For more examples see perldoc DBI and perldoc DBD::mysql or online
versions available at e.g.
http://cpan.uwinnipeg.ca/htdocs/DBI/DBI.html.

Note: For clarity, the following examples contain basic Perl code
snippets which do not use my or other recommended practices. For happy
Perl programming always use the pragma

use strict;
use warnings;

at the start of your scripts.
Connecting to a database

use DBI;
$dbh = DBI->connect('DBI:mysql:databasename', 'username', 'password'
                  ) || die "Could not connect to database: $DBI::errstr";
# (insert query examples here...)
$dbh->disconnect();

Connecting to a different host:


$dbh = DBI->connect('DBI:mysql:databasename;host=db.example.com',
'username', 'password',
                   { RaiseError => 1 }
                  );

Simple query

$dbh->do('CREATE TABLE exmpl_tbl (id INT, val VARCHAR(100))');
$dbh->do('INSERT INTO exmpl_tbl VALUES(1, ?)', undef, 'Hello');
$dbh->do('INSERT INTO exmpl_tbl VALUES(2, ?)', undef, 'World');
$c = $dbh->do('DELETE FROM exmpl_tbl WHERE id=1');
print "Deleted $c rows\n";

(Do not use $dbh->do() for SELECT statements because it does not
return a statement handle, making it impossible to fetch data)
Typical query

$sth = $dbh->prepare('SELECT val FROM exmpl_tbl WHERE id=1');
$sth->execute();
$result = $sth->fetchrow_hashref();
print "Value returned: $result->{val}\n";

Query using placeholders

$sth = $dbh->prepare('SELECT id FROM exmpl_tbl WHERE val=?',
undef, 'World');
@result = $sth->fetchrow_array();
print "ID of World is $result[0]\n";

Execute and fetch in one command

$sth = $dbh->prepare('SELECT * FROM exmpl_tbl');
$results = $dbh->selectall_hashref('SELECT * FROM exmpl_tbl', 'id');
foreach my $id (keys %$results) {
 print "Value of ID $id is $results->{$id}->{val}\n";
}

Password Regular Expression in perl example

 Only contains alphanumeric and the following special characters: !@#$%^&*
   Contains at least 1 of the special characters in the list above
   The required special character can appear anywhere in the string
(for example: !abc, a!bc, abc!)


The regular expression you're looking for is:

/^(?=.*[\!\@\#\$\%\^\&\*])[A-Za-z0-9\!\@\#\$\%\^\&\*]+$/

which will guarantee the string contains one of your special
characters using (?=) positive lookahead.


OR

^(?=.*?[!@#$%\^&*])((?!_)[\w!@#$%\^&*])+$

It looks ensure the special character is found anywhere in the string.
Once it finds it, it matches the rest of the string as long as the
string consists of only word characters, digits, and the special
characters.

Edit: The negativelookahead prevents _ (underscore).


OR


Say you want minimum requirements of "at least one non-alphanumeric
character, at least 8 characters". Use two look-aheads:

^(?=.*[^a-zA-Z0-9])(?=.{8,}$)

Other than that - let users choose the passwords they like.

How to Manage MySQL Transactions and AutoCommit in Perl DBI

When working with databases in Perl using DBI, you often want to group multiple operations into a single transaction. You can do this by using $dbh->begin_work (which temporarily turns off AutoCommit) and then calling $dbh->commit when you are done.

# 1. Connect to the database
my $dbh = DBI->connect("DBI:mysql:database_name", "username", "password");

# 2. Prepare your SQL statement or stored procedure
my $sth = $dbh->prepare("call sp_get_workitems (1,1)");

# 3. Start the transaction 
# (This is equivalent to setting $dbh->{'AutoCommit'} = 0;)
$dbh->begin_work or die $dbh->errstr;      

# 4. Execute the query and fetch results
$sth->execute();
my ($result) = $sth->fetchrow_array();

# 5. Commit the transaction to save changes
$dbh->commit;

Complete Guide to Perl File Test Operators and Syntax


File test operators in Perl allow you to check the status, permissions, and type of files or directories.

OperatorDescription
-rFile is readable by effective uid/gid.
-wFile is writable by effective uid/gid.
-xFile is executable by effective uid/gid.
-oFile is owned by effective uid.
-RFile is readable by real uid/gid.
-WFile is writable by real uid/gid.
-XFile is executable by real uid/gid.
-OFile is owned by real uid.
-eFile exists.
-zFile has zero size (is empty).
-sFile has nonzero size (returns size in bytes).
-fFile is a plain file.
-dFile is a directory.
-lFile is a symbolic link.
-pFile is a named pipe (FIFO), or Filehandle is a pipe.
-SFile is a socket.
-bFile is a block special file.
-cFile is a character special file.
-tFilehandle is opened to a tty.
-uFile has setuid bit set.
-gFile has setgid bit set.
-kFile has sticky bit set.
-TFile is an ASCII text file (heuristic guess).
-BFile is a "binary" file (opposite of -T).
-MScript start time minus file modification time, in days.
-ASame for access time.
-CSame for inode change time (Unix, may differ for other platforms).