Archive for category perl hacks
Program to display complete information about a file: Perm, inode, acl bits.
Posted by admin in perl hacks on June 14th, 2009
#!/usr/bin/perl
use File::stat;
$pwd = (getpwuid($<))[1];
print "$pwd";
system "stty -echo";
print "Password: ";
chomp($word =
Word wrap in perl
Posted by admin in perl hacks on June 14th, 2009
Word wrap plays an important role while displaying any output to the standard output or a file. This is used to display the output neatly and in a ordered way.
#!/usr/bin/perl -w
use strict;
use Text::Wrap;
undef $/;
print wrap('', '', split(/\s*\n\s*/, <>));
use Text::Wrap qw(&wrap $columns);
use Term::ReadKey qw(GetTerminalSize);
($columns) = GetTerminalSize();
print $columns;
($/, $\) = ('', "\n\n"); # read by paragraph, output 2 newlines
while (<>) { # grab a full paragraph
s/\s*\n\s*/ /g; # convert intervening newlines to spaces
print wrap('', '', $_); # and format
}
Print the kind of number
Posted by admin in perl hacks on June 14th, 2009
Print whether a number is integer, decimal, positive, negative .. etc.,
#!/usr/bin/perl
sub getnum {
use POSIX qw(strtod);
my $str = shift;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
$! = 0;
my($num, $unparsed) = strtod($str);
if (($str eq '') || ($unparsed != 0) || $!) {
return;
} else {
return $num;
}
}
sub is_numeric { defined scalar &getnum }
$_ = "-0.65";
if (/\D/){
print "is a nondigit"; }
else {
print "is a digit or someother"; }
# warn "is a nondigit" if /\D/;
warn "not a natural number" unless /^\d+$/;
warn "not a integer" unless /^[-+]?\d+$/;
warn "not an decimal number" unless /^-?\d+\.?\d*$/;
print is_numeric( defined scalar &getnum);
print getnum("A143");
Program to test with different basic functions in perl
Posted by admin in perl hacks on June 14th, 2009
Remove to comments to test different functions in perl.
#!/usr/bin/perl
# $substr = substr($string,$offset,$count)
# $substr = substr($string,$offset)
# substr($string,$offset,$count) = $newstring; is used to replace the string with the new
# string
# substr($string,$offset) = $newstring;
# The number of A's in the unpack function is the number of variables towards left
# ($str1,$str2,$str3,$final) = unpack("A5 x3 A6 A8 A*",$data)
# split at five byte boundaries
# @fivers = unpack("A5" x (length($string)/5), $string);
# split individual characters
# @chars = unpack("A1" x length($string),$string);
# ---------------------------------------------------------------------------------
use Text::Tabs;
sub cut2fmt {
my(@positions) = @_;
my $template = '';
my $lastpos = 1;
foreach $pos (@positions) {
$template = "A" . ($pos-$lastpos) . " ";
$lastpos = $pos;
}
$template .= 'A*';
return $template;
}
$newstring = "is also a sample string";
$string = q{this is a sample string to be tested on different functions};
$string1 = q{this is a sample string to be tested on different functions};
$data = q{this is a sample string to test the unpack function};
$substr = substr($string,5,18);
$substr1 = substr($string,5);
print $substr . "\n";
print $substr1 . "\n";
substr($string1,5,18) = $newstring;
print $string1 . "\n";
$_ = $data;
$data = s/(\b)/ /;
print "$data";
($first,$last) = unpack("A4 A*", $data);
print $first . "\n";
print $last;
# -----------------------------------------------------------------------------------
# converting between ASCII characters and values
# this is to demonstrate and use function "ord" and "chr"
# Use ord to convert character to a number or use chr to convert number to character
# $char = sprintf("%c", $num); # slower than chr($num)
# printf("Number %d is character %c\n", $num, $num);
$num = 70;
$char = sprintf("%c", $num); # slower than chr($num)
print "$char" . "\n";
printf("Number %d is character %c\n", $num, $num);
# "unpack" and "pack" functions can also be used to convert many characters
$string = "test string\n";
@ASCII = unpack("C*", $string);
print "@ASCII"; #see the difference
print @ASCII; #see the difference
foreach $val (@ASCII) {
print $val . " ";
}
print "\n";
$STRING = pack("C*", @ASCII);
print "$STRING";
# -----------------------------------------------------------------------------------
# processing a string one character at a time
# and caluculating the checksum of a string
$string = "characters string";
%seen = ();
$sum = 0;
@array = split(//, $string);
print "@array\n";
@array1 = unpack("C*", $string);
foreach $num (@array1) {
$sum += $num;
printf("%c ", $num);
}
print "\n";
while ($string =~ /(.)/g) {
print "$1 ";
$seen{$1}++;
}
print "\nunique characters are ", sort(keys %seen), "\n";
print "the checksum of \"$string\" is $sum" . "\n";
# -----------------------------------------------------------------------------------
# reversing a string by word or character
# fucntions used are "reverse" , "join" and "split"
$string = "sample string to test these characters";
# $revstr = reverse($string);
@words = split(" ", $string);
@revwor = join(" ", reverse @words);
print "@revwor";
# print "$revstr";
# -----------------------------------------------------------------------------------
# expanding and compressing tabs
# functions used are "expand" and "unexpand"
# use Text::Tabs module
$string = "sample text to test these characters\n";
while ($string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e) { print "in the loop";}
print "$string";
$tabstop = 8;
# while(<>) {print expand($_)}
# while(<>) {print expand($_)}
# -----------------------------------------------------------------------------------
# expanding variables in user input
use vars qw($rows $coloums);
no strict 'refs';
my $text;
# print "enter number of rows :";
# chomp($rows =
$string = " sample test string to test trim nature ";
$string =~ s/^\s+//;
$string =~ s/\s+$//g;
print $string;
$| = 0;
print "$%";
print "$=";
print "sampel";
Slow print the text!!
Posted by admin in perl hacks on June 14th, 2009
Print the desired text slowly using perl.
#!/usr/bin/perl
$DELAY = ($ARGV[0] =~ /^-([.\d]+)/) ? (shift, $1) : 1;
$| = 1;
$_ = "Print this";
while ($_) {
for (split(//)) {
print;
select(undef,undef,undef, 0.005 * 20);
}
$_ = "";
}
DATABASE ACCESS USING PERL
Posted by admin in perl hacks on May 9th, 2009
INSERT DELETE AND MODIFY SEARCH DATABASE BASED ON FILTERS
#!/usr/bin/perl
use DBI;
use DBD::mysql;
# CONFIG VARIABLES
$platform = “mysql”;
$database = “<databasename>”;
$host = “localhost”;
$port = “3306?;
$tablename = “<tablename>”;
$user = “<username>”;
$pw = “<password>”;
$i=0;
$j=1;
# DATA SOURCE
$dsn = “dbi:mysql:$database:$host:$port”;
# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);
# IF THERE IS AN ERROR CONNECTING TO THE DATABASE
if (not $connect) {
print “The connection attempt failed for the following reason:$DBI::errstr”;
}
sub display
{
# TAKING THE FILTER TO DISPLAY THE FIELDS
local $j=0;
$filter = $_[1];
$coltodisp = $_[0];
# PREPARE THE QUERY
$query = “SELECT * FROM $tablename where $coltodisp=”$filter”";
# $query = “show tables”;
$query_handle = $connect->prepare($query);
# EXECUTE THE QUERYS
$query_handle->execute();
# LOOP THROUGH
while (@row= $query_handle->fetchrow_array()) {
$i = 0;
print “nn”;
print “***********************************************************************************************************” . “n”;
print “ $j”;
$j += 1;
print “n***********************************************************************************************************” . “n”;
for $tables (@row) {
print “n—————–” . “n”;
print “$colo[$i]” . “n”;
print “——————-” . “n”;
print “$tables” . “n”;
$i += 1;
}
}
$j -= 1;
print “n$j matchings foundn”;
$rc = $query_handle->finish;
}
sub dbsearch {
$coltosearch = $_[0];
$pattern = $_[1];
$query = “select * from $tablename where $coltosearch like “%$pattern%”";
$query_handle = $connect->prepare($query);
$query_handle->execute();
while (@row= $query_handle->fetchrow_array()) {
$i = 0;
print “nn”;
print “***********************************************************************************************************” . “n”;
print “PATTERN MATCHING $j”;
$j += 1;
print “n***********************************************************************************************************” . “n”;
for $tables (@row) {
print “n—————–” . “n”;
print “$colo[$i]” . “n”;
print “——————-” . “n”;
print “$tables” . “n”;
$i += 1;
}
}
$j -= 1;
print “n$j matchings foundn”;
$rc = $query_handle->finish;
}
# TAKING TABLES INFORMATION IN TO ARRAY
$query1 = “DESCRIBE $tablename”;
$query1_handle = $connect->prepare($query1);
$query1_handle->execute();
print “*********************************************************************************************************n”;
print “Coloums information in the table” . “n”;
print “*********************************************************************************************************n”;
while(@coloum= $query1_handle->fetchrow_array()) {
$colo[$i] = $coloum[0];
print “$i. “;
print “$coloum[0]” . “n”;
$i += 1;
}
print “*********************************************************************************************************nn”;
while(1) {
# TAKING INPUT FROM USER TO INSERT,DELETE,EDIT,SEARCH
print <<EOP;
Enter some :
1) 1 for insert
2) 2 for delete
3) 3 for edit
4) 4 for display
5) 5 for search
EOP
print “nEnter some number to carryout the task ::”;
$num = <>;
if ($num == 1) {
$i = 0;
$query = “INSERT INTO $tablename (”;
for $val (@colo) {
print “Enter $val to insert :: “;
$toinsert[$i] = <>;
chomp($toinsert[$i]);
$i += 1;
$query = $query . “$val, “;
}
$query = $query . “) VALUES (”;
for $val1 (@toinsert) {
$query = $query . “‘$val1?, “;
}
$query = $query . “)”;
print “n”;
$query =~ s/,s+)/)/g;
$query_handle = $connect->prepare($query);
$query_handle->execute();
}
elsif ($num == 2) {
print “Follow the to delete a particular row”;
print “ENter the coloum name to filter table display:: “;
$coltodisp = <>;
chomp($coltodisp);
print “Enter $coltodisp :: “;
$temp = <>;
chomp($temp);
$arbit = &display($coltodisp,$temp);
print “Do you want to delete the entry (y/n)?”;
$ans = <>;
chomp($ans);
if($ans eq “y” || $ans eq “yes”)
{
$query = “DELETE from $tablename where $coltodisp=”$temp”";
$query_handle = $connect->prepare($query);
$query_handle->execute();
}
}
elsif($num == 3) {
print “ENter the coloum name to filter table display:: “;
$coltodisp = <>;
chomp($coltodisp);
print “Enter $coltodisp :: “;
$temp = <>;
chomp($temp);
print “Enter the coloum you want to edit:: “;
$coltoedit = <>;
chomp($coltoedit);
$arbit = &display($coltodisp,$temp);
print “Enter the value to edit:: “;
$edittoval = <>;
chomp($edittoval);
print “Do you really want to edit the field entry (y/n)?”;
$ans = <>;
chomp($ans);
if($ans eq “y” || $ans eq “yes”)
{
print “:”;
$query = “UPDATE $tablename SET $coltoedit=’$edittoval’ WHERE $coltodisp=”$temp”";
$query_handle = $connect->prepare($query);
$query_handle->execute();
}
}
elsif($num == 4) {
print “Enter the Coloum name to filter table display:: “;
$coltodisp = <>;
chomp($coltodisp);
print “Enter $coltodisp :: “;
$temp = <>;
chomp($temp);
$arbit = &display($coltodisp,$temp);
}
elsif($num == 5) {
print “Enter the coloum name to search for a pattern:: “;
$coltosearch = <>;
chomp($coltosearch);
print “Enter the pattern to be searched:: “;
$pattern = <>;
chomp($pattern);
&dbsearch($coltosearch,$pattern);
}
}


Recent Comments