Friday, May 24, 2013

Perl's simple parallel processing fork manager


-----------------
fork_manager.pl
-----------------
use Parallel::ForkManager;

#$pm = new Parallel::ForkManager($MAX_PROCESSES);
$pm = new Parallel::ForkManager(33);


foreach my $command (@commands) { $pm->start and next; #fork the child and move next look in parent system( $command ); #child's work $pm->finish; #child ends here };

$pm->wait_all_children; #wait till all children are complete


Saturday, February 2, 2013

menu driven script for creating and storing the INDEX to a file

Following are the functions of the script:

1) show the index stored in file
2) search the index by keyword
3) add the record to index (key - value pair).

------------------------------------------------------------------------------------
menu_driven_create_store_index.pl

#!/usr/bin/perl -w
#use strict;
use Switch;
use Data::Dumper;

MENU:
system("clear");

showMenu();
my $choice = getChoice();

decide($choice);

askForExit();

#------------------------------SUBROUTINES----------------------------

sub showMenu {
  print "---------------------MENU-------------------\n";
  print "1)Show Index\n2)Search Index by keword(s)\n3)Add tutorial to the Index\n4)Exit\n";
  print "--------------------------------------------\n";
  print "\nPlease enter choice: ";
}


sub getChoice {
  my $choice = <>;
  chomp $choice;
  return $choice;
}


sub decide {
  my $choice = shift;
  switch ($choice) {
    case 1 {showIndex();}
    case 2 {
             my $keword = shift;
             searchByKeyword($keword);
           }
    case 3 {addTutorialToIndex();}
    else {print "Wrong choice\n";}
  }
}

sub showIndex {
  open FH, 'index' or die "cant open index : $!";
  local $/;
  my $hashref = eval <FH>;
  close FH;

  print "\n---------------INDEX-------------\n";
  foreach my $key (keys %$hashref) {
    print "> $key => ", $hashref->{$key}, "\n";
  }
}

sub addTutorialToIndex {

  open  FH1, 'index' or die "cant open index : $!";
  local $/;
  my $hashref = eval <FH1>;
  close FH1;

  $/ = "\n";

  $hashref = {} unless ($hashref);

  print "\nEnter the index key:\n";
  my $key = <>;
  chomp($key);

  print "\nEnter the index value i.e. filename in which the tutorial is stored\n";
  my $value = <>;
  chomp($value);

  if (exists $hashref->{$key}) {
    print "\n\nThe index key already exists.\nDo you want to override?(y/n)\n";
    my $choice = acceptYesNoChoice();
    return if ($choice eq 'n');
  }
  $hashref->{$key} = $value;

  open  FH, '>', 'index' or die "cant open index : $!";
  print FH Dumper($hashref);
  close FH;
  print "\n\n Data added to the Index.";
}

sub acceptYesNoChoice {
  my $choice;
  while (1) {
    $choice = <>;
    chomp $choice;
    return $1 if ($choice =~ /^(y|n)$/);
    print "\n\nInvalid Choice!!\nPlease enter valid choice (y/n)";
  }
}

sub askForExit {
 print "\n\nDo you wish to continue(y/n):\n";
  $choice = acceptYesNoChoice();
  goto MENU if ($choice eq 'y');
}

---------------------------------------------------------------

>perl menu_driven_create_store_index.pl

---------------------MENU-------------------
1)Show Index
2)Search Index by keword(s)
3)Add tutorial to the Index
4)Exit
--------------------------------------------

Please enter choice: 1

 choice = 1

---------------INDEX-------------
> calling subroutine => ex1.pl
> When you pass scalars to subroutine, they are passed by reference => ex2.pl
> Setting the default values for arguments => ex3.pl


Do you wish to continue?(y/n):



Likewise you can carryout other functions and you can add more functions according to you need.

Friday, January 18, 2013

saving perl data structure to the file and reading it back

We can save the data structure like hashes, arrays, and their combinations to local file and read them back, which can be called as serializing and deserialzing the DS in perl.

Example 1: writing hash to a file and red it back

save_and_read_perl_ds_to_file.pl


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

system("clear");

#sample hash
my %h1 = (
           k1 => 'v1',
           k2 => 'v2',
           k3 => 'v3'
         );

print "before writing to a file:\n";
print Dumper(\%h1);

#write perl hash to a file using data dumper

open  FH, '>', 'ds_file.csv' or die "cant open file";
print FH Data::Dumper->Dump([\%h1]); #NOTE [ %h1 ] unlike print Dumper(\%h1);
close FH;


#read the hash from file
open FH, 'ds_file.csv' or die "$!";

local $/;  #slurp mode http://perl-savvy.blogspot.in/2013/01/perl-slurp-mode.html
$hashref = eval <FH>;

close FH;

print "\nafter writing and reading back again :\n ";
print Dumper($hashref);

-----------------------------------------------------------------------


ds_file.csv


$VAR1 = {
          'k2' => 'v2',
          'k1' => 'v1',
          'k3' => 'v3'
        };



As you can see the contents of file where in we dumped the hash, in the perl file save_and_read_perl_ds_to_file.pl, we do eval on file_handle of this file, which returns the hash reference.






perl slurp mode


Perl can change the mode of how to read a file.

$/
The input record separator, newline by default. $/ may be set to a value longer than one character in order to match a multi-character delimiter. If $/ is undefined, no record separator is matched, and <FILEHANDLE>will read everything to the end of the current file.   

Example:

open FILEHANDLE, 'somefile.txt' or die $!;
local $/; my $string = <FILEHANDLE>;




Friday, January 11, 2013

AJAX - perl


CALLING SERVER SIDE PERL SCRIPT THROUGH AJAX

Create an XMLHttpRequest Object:
      
      var xmlhttp;
      if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
      else
     {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }

USING GET METHOD:

xmlhttp.open("GET","demo_get.pl",true);
xmlhttp.send();

OR

xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();

USING POST METHOD:
xmlhttp.open("POST","demo_get.pl",true);
xmlhttp.send();

OR

xmlhttp.open("POST","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();

Server Response:
xmlhttp.responseText //get the response data as a string

xmlhttp.responseXML  //get the response data as XML data

The onreadystatechange event:

When readyState is 4 and status is 200, the response is ready:

xmlhttp.onreadystatechange=function()

  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    here_is_response=xmlhttp.responseText;
    }
  }

  The above function is automatically called when the status of response is changed. Specifically used while AJAX, which is TRUE value in caller.

While getting the response for Synchronous call, which is FALSE value in caller, we use it straight forward:

 xmlhttp.open("GET","demo_get.pl?resultFileName="+resultFileName,false);
 xmlhttp.send();
 reply=xmlhttp.responseText; 

here, server side script can by anything: php, perl, asp, jsp, etc







html form onsubmit event with two submit buttons

It is not possible to know which submit button is clicked in onsubmit() of form, when there are two submit buttons on the same form.


e.g.


<html>
<head>
<script>
function verifySubmit()
{
   alert("in verifySubmit");
   return false;
}
</script>
</head>

<body>

alohaaa
<form name="frm1" onsubmit="return verifySubmit();">
<input type="text" name="fname">
<input type="submit" value="Submit">
<input type="submit" value="Delete">

</form>

</body>
</html>



In above case, there is no way out to perform different operations depending on which submit is clicked; submit or delete.



SOLUTION ::





<script language="javascript" type="text/javascript">
    function verifyData(button) {
        // validate
       var returnVal;
        switch (button.value) {
            case "submit1":   
                alert("submit1");
                returnVal=true;
                break;
            case "submit2":
                alert("submit2");
                returnVal=false;
                break;
        };
        return returnVal;
    }

</script>

<form method="post">
    <input type="submit" value="submit1" onclick="return verifyData(this);">
    <input type="submit" value="submit2" onclick="return verifyData(this);">
</form>




NOTE:

  • Action is not present means, submit would reload this page
  • If onclick is true, it will submit the request.
  • If onlclick is false, it will not submit the request.







Thursday, September 27, 2012

Delete elements from an array and purge the deleted values.


#!/usr/bin/perl

# create an array
my @arr = (1..10);

#delete even indexed values
foreach (0..$#arr) {
  delete $arr[$_] if ($_ % 2);
}

# print the array length and array
print 'array length = ', scalar(@arr), " and array = @arr";
print "\n\n";

use Data::Dumper;
print Dumper(\@arr);

print "\n\n";
#purge the deleted elements.
@arr = grep defined, @arr;
print 'array length = ', scalar(@arr), " and array = @arr";

print "\n\n";
print Dumper(\@arr);


-------------------------------------------------------------------------------------
output ::

array length = 9 and array = 1  3  5  7  9

$VAR1 = [
          1,
          undef,
          3,
          undef,
          5,
          undef,
          7,
          undef,
          9
        ];


array length = 5 and array = 1 3 5 7 9

$VAR1 = [
          1,
          3,
          5,
          7,
          9
        ];