Showing posts with label Perl. Show all posts
Showing posts with label Perl. Show all posts

Saturday, May 08, 2010

Perl: Reading Processes from Unix

Here is a way using pipes

open(PS_F, "ps -f|");

while () {
($uid,$pid,$ppid,$restOfLine) = split;
# do whatever I want with the variables here ...
}

close(PS_F);

You can also try with split(/\s+/,$_)

Good Presentation on Patterns

http://www.cs.clemson.edu/~malloy/courses/patterns/slides/

Friday, May 07, 2010

Perl and Unix Processes control

Here is a script fot this

http://aplawrence.com/Unix/perlforkexec.html

http://docstore.mik.ua/orelly/perl/cookbook/index.htm

Wednesday, April 28, 2010

Itrating Hashes in Perl: Many ways

1) If you just want the keys and do not plan to ever read any of the values, use keys():

foreach my $key (keys %hash) { ... }

2) If you just want the values, use values():

foreach my $val (values %hash) { ... }

3) If you need the keys and the values, use each():

keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
while(my($k, $v) = each %hash) { ... }

4) If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():

%h = (a => 1, b => 2);

foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}

Command line options with Perl: EG

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std;
use vars qw/ %opts /;

getopts('he:c:', \%opts );
usage() if $opts{h};
usage() if($opts{e} eq "" or $opts{c} eq "");

sub usage(){
print "This program should be used as below\n";
print "usage: $0 [-h] [e petrol] [-c elgi]\n";
print " -h : this (help) message\n";
print " -e : energy name\n";
print " -c : compressor name\n";
print " example: $0 -e petrol -c elgi\n";
exit;
}

Sunday, April 25, 2010

Tips and Tricks in Perl

Create an array from a string
@months = split ' ', "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
or
@months = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/

Create a string from an array.
@stuff = ("hello", 0..9, "world"); $string = join '-', @stuff

Generate an array with even numbers from 1 to 100
perl -le '@even = grep {$_ % 2 == 0} 1..100; print "@even"'

The spaceship operator <=>
my @numbers = (-59, 99, 87, 1900, 42, 1, -999, 30000, 0);
my @sorted = sort { $a <=> $b } @numbers;
print "@sorted\n";
# output: -999 -59 0 1 42 87 99 1900 30000

Saturday, April 24, 2010

Random password generator in perl

Here is a oneliner for this

perl -le 'print map { ("a".."z")[rand 26] } 1..8'

Here the map function executes ("a".."z")[rand 26] code 8 times (because it iterates over the dummy range 1..8). In each iteration the code chooses a random letter from the alphabet. When map is done iterating, it returns the generated list of characters and print function prints it out by concatenating all the characters together.

If you also wish to include numbers in the password, add 0..9 to the list of characters to choose from and change 26 to 36 as there are 36 different characters to choose from:

perl -le 'print map { ("a".."z", 0..9)[rand 36] } 1..8'

If you need a longer password, change 1..8 to 1..20 to generate a 20 character long password

From http://www.catonmat.net/blog/perl-one-liners-explained-part-four/

Friday, April 23, 2010

Getopts::Long HowTo in Perl

Here is an excellent link

http://www.devshed.com/c/a/Perl/Using-GetoptLong-More-Command-Line-Options-in-Perl/

Thursday, April 22, 2010

Callback function in Perl: EG

#!/usr/bin/perl
#use strict;
#use warnings;

my $adder = sub {
my ( $arg1, $arg2 ) = @_;
return $arg1 + $arg2;
};

my $multiplier = sub {
my ( $arg1, $arg2 ) = @_;
return $arg1 * $arg2;
};

sub doit {
my ($action, $arg1, $arg2) = @_;
return $action->( $arg1, $arg2 );
}

# This returns 30
my $val1 = doit( $adder, 10, 20 );

# This returns 200
my $val2 = doit( $multiplier, 10, 20 );

Automatically include many file from many directory

In case you write a perl program to include a require with lot of file here is a small program for that.

#!/usr/bin/perl
use strict;
use warnings;
&putAllIncludeFiles;
sub putAllIncludeFiles{
        my @thefiles=readAllFilesFromDirectories("/home/tullas/lesson/framework/lib","/home/tullas/lesson/framework/conf");
        my $f;
        foreach $f (@thefiles){
                require $f;
        }
}
sub readAllFilesFromDirectories{
   my $filename;
   my @filenames;
   foreach (@_) {
        opendir ( DIR, $_ ) || die "Error in opening dir $_\n";
        while( ($filename = readdir(DIR))){
                unless ( ($filename eq ".") || ($filename eq "..") ){
                        #print("$filename\n");
                        push @filenames,$_ . "/" . $filename;
                        $filename = "";
                }
        }
   }
   return @filenames;
   closedir(DIR);
}

Wednesday, March 31, 2010

File to Hash Technique: Multiple values

If you have a file like below
#File test.txt
usa, phili
usa, cali
france, paris
france, marcille
india, delhi
usa, atlanta

Script to do that is below.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %table = ();

open(FILE, "test.txt") or die("Unable to open manifest due to $!");
while ()
{
chomp;
my ($key, $val) = split /, /;
$table{$key} .= exists $table{$key} ? ",$val" : "$val";
}
close(FILE);
print Dumper(\%table);


Here is the output.

$VAR1 = {
'usa' => ',phili,cali,atlanta',
'france' => ',paris,marcille',
'india' => ',delhi'
};

Perl Reference

Say you have a file like this.

Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA

We need an output like below.

Finland: Helsinki.
Germany: Berlin, Frankfurt.
USA: Chicago, New York, Washington.

To do this it would be good to use perl references as below

my %table;
while (<>) {
chomp;
my ($city, $country) = split /, /;
$table{$country} = [] unless exists $table{$country};
push @{$table{$country}}, $city;
}
foreach $country (sort keys %table) {
print "$country: ";
my @cities = @{$table{$country}};
print join ', ', sort @cities;
print ".\n";
}

More explanation on references is here http://perldoc.perl.org/perlreftut.html

Tuesday, August 18, 2009

Unencrypting a directory of gpg files in perl

Here is a way to unencrypt all files in a directory which contain many gpg files

my @FList=`ls *.gpg`;
foreach $FFile (@FList)
{
open (MYFILE, "echo $secret | gpg --batch --passphrase-fd 0 --decrypt $FFile | cut -c2-5 |");
while (){
print "Line # ".$i." ".$_;
$i++;
}
close MYFILE;