Saturday, July 9, 2011

File::Base​name Module Example in perl

use File::Basename;

($name,$path,$suffix) = fileparse($fullname,@suffixlist);

$name = fileparse($fullname,@suffixlist);
$basename = basename($fullname,@suffixlist);
$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.

mysql AutoCommit in perl

my $dbh= DBI->connect(............  );

my $sth = $dbh->prepare("call sp_get_workitems (1,1)");
$dbh->begin_work  or die $dbh->errstr;       #$dbh->{'AutoCommit'} =
0; same as begin_work
$sth->execute();
my ($result)= $sth->fetchrow_array();

$dbh->commit;

perl file test syntax

It checks whether the directory exists or not. There are many more
file test operations available, such as below:

  1. -r File is readable by effective uid/gid.
  2. -w File is writable by effective uid/gid.
  3. -x File is executable by effective uid/gid.
  4. -o File is owned by effective uid.
  5. -R File is readable by real uid/gid.
  6. -W File is writable by real uid/gid.
  7. -X File is executable by real uid/gid.
  8. -O File is owned by real uid.
  9. -e File exists.
 10. -z File has zero size (is empty).
 11. -s File has nonzero size (returns size in bytes).
 12. -f File is a plain file.
 13. -d File is a directory.
 14. -l File is a symbolic link.
 15. -p File is a named pipe (FIFO), or Filehandle is a pipe.
 16. -S File is a socket.
 17. -b File is a block special file.
 18. -c File is a character special file.
 19. -t Filehandle is opened to a tty.
 20. -u File has setuid bit set.
 21. -g File has setgid bit set.
 22. -k File has sticky bit set.
 23. -T File is an ASCII text file (heuristic guess).
 24. -B File is a "binary" file (opposite of -T).
 25. -M Script start time minus file modification time, in days.
 26. -A Same for access time.
 27. -C Same for inode change time (Unix, may differ for other platforms)

How to create multi-dime​nsional array in perl?

You get a one-dimensional array because the array @a1 is expanded
inside the parens. So, assuming:

my @a1 = (1,2);
my @a2 = (@a1,3);

Then your second statement is equivalent to my @a2 = (1,2,3);.

When creating a multi-dimensional array, you have a few choices:

Direct assignment of each value
Dereferencing an existing array
Inserting a reference

The first option is basically $array[0][0] = 1; Not very exciting.

The second is doing this: my @a2 = (\@a1, 3); Note that this makes a
reference to the namespace for the array @a1, so if you later change
@a1, the values inside @a2 will also change. Not always a recommended
option.

A variation of the second option is doing this: my @a2 = ([1,2], 3);
The brackets will create an anonymous array, which has no namespace,
only a memory address, and will only exist inside @a2.

The third option, a bit more obscure, is doing this: my $a1 = [1,2];
my @a2 = ($a1, 3); It will do exactly the same thing as 2, only the
array reference is already in a scalar variable, called $a1.

Note the difference between () and [] when assigning to arrays.
Brackets [] create an anonymous array, which returns an array
reference as a scalar value (e.g. that can be held by $a1, or $a2[0]).

Parens on the other hand do nothing at all really, except change the
precedence of operators.

Consider this piece of code:

my @a2 = 1, 2, 3;
print "@a2";

This will print 1. If you use warnings, you will also get a warning
such as: Useless use of a constant in void context. What happens is
basically this:

my @a2 = 1;
2, 3;

Because commas (,) have a lower precedence than equalsign =. (See
"Operator Precedence and Associativity" in perldoc perlop)

What parens do is simply negate the default precedence of = and ,, and
group 1,2,3 together in a list, which is then passed to @a2.

So, in short, brackets [] have some magic in them: They create
anonymous arrays. Parens () just change precedence, much like in math.

There is much to read in the documentation. Someone here once showed
me a very good link for dereferencing, but I don't recall what it is.
In perldoc perlreftut you will find a basic tutorial on references.
And in perldoc perldsc you will find documentation on data structures
(thanks Oesor for reminding me).

What does this split expression mean in Perl?

while (<>) {
 chomp;
 print join("\t", (split /:/)[0, 2, 1, 5] ), "\n";
}

What does (split /:/)[0, 2, 1, 5] mean here?


It means

my @fields            = split /:/, $_;
my @fields_to_display = ($fields[0], $fields[2], $fields[1], $fields[5]);

create a list by splitting the line on :, then take elements 0,2,1,5
of this list

What's the difference between exists and defined

defined checks the value of the variable, exists checks if it has been
previously declared/initialized. If it exists, plain and simple.

E.g.:

$hash{$key} = undef;
# various return values:
exists  $hash{$key};  # true
defined $hash{$key};  # false
$hash{$key};          # false

$hash{$key} = 0;
# various return values:
exists  $hash{$key};  # true
defined $hash{$key};  # true
$hash{$key};          # false
exists $hash{$foo};   # false

In Perl,is there a way to do simple arithmetic inside quotes?

$i = 5;
print "{$i*10}";

Sometimes I may need to do things like above,but Perl doesn't
interpret it the way I want,and I can only do it with another
variable.Is there a trick?



I suggest you use "printf":

printf("%s",$i*10);

How to copy keys from hash to array without duplicates​?

#Method 1:

You could make use of List::MoreUtils's uniq function:

use List::MoreUtils qw( uniq );

@a = uniq @a, keys %h;


#Method 2:
Convert the values you want into hash keys, then extract them

my %foo = map { $_ => 1  } @a, keys %h;
print sort keys %foo;


Method 3:
If you have Perl 5.10 and later, you can use smart matching (~~):

for my $key (keys %h) {
   push @a, $key unless $key ~~ @a;
}