Tuesday, December 23, 2008

Parallel Programming with Perl

Perl have a great support for parallel execution since version 5.6. Shared variables guarantees you to modify the state at the same time from different threads, without the internal state of the variable will become corrupted.

#!/usr/bin/perl
use strict;
use threads;
use threads::shared;

$|=1; # autoflush on

my $running = 1;
share $running;

print "Press enter to stop\n";

my $job = async {
  while($running > 0) {
    print ".";
    sleep 1;
  }
};

my $enter= <STDIN>;
$running = 0;
$job->join();

Monday, December 15, 2008

Understanding class inheritance in Perl

By using the global variable @ISA you could extend classes in Perl. Like C++, Perl supports single and multiple class inheritance. 

In this sample, class B derives from base class A.

#!/usr/bin/perl
use strict;
package A;

sub new {
  my $class = shift;
  my %args = @_;

  my $this = {
    M1 => $args{"P1"},
    M2 => $args{"P2"}
    };

    return bless ($this, $class);
}

package B;
our @ISA = "A";

sub new {
  my $class = shift;
  my %args = @_;

  my $this = $class->SUPER::new(@_);

  $this->{"M3"} = $args{"P3"};

  return(bless($this, $class));
}

my $a = new B(P1 => "bbb", P2 => "blue", P3 => "jjj");

print($a->{'M1'} . "\n");
print($a->{'M2'} . "\n");
print($a->{'M3'} . "\n");

Wednesday, December 10, 2008

Active Server Pages with Perl

You can create a simple framework to render html pages by using templates and embedded Perl code.

The html template page
<html> 
  <body>
    <h1><perl>localtime(time());</perl></h1>  
  </body>
</html>

The html rendering engine
#!/usr/bin/perl -w
use strict;

sub generateHTML {
  my @pass1 = split(/<\/perl>/, shift);
  my @html;

  foreach my $e (@pass1) {
  my @pass2 = split(/<perl>/, $e);  
  my $value;
  push(@html, $pass2[0]);
  if (scalar(@pass2) > 1) {
      $value = eval($pass2[1]);
      push(@html, $value);
    }
  }
  return join("", @html);
}

Friday, December 5, 2008

Object oriented development with Perl

This sample code demonstrates how to implement operator overloading with Perl.
#!/usr/bin/perl -w
use strict;

my $n = new Number(5);
$n = $n + 1 - 2;

print "$n\n";

# The class implementation
package Number;

use overload '+' => \&add;
use overload '-' => \&subtract;
use overload '""' => \&toString;

sub new {
  my $class = shift;
  my $this = { size => shift };
  return bless ($this, $class);
}

sub subtract {
  my ($this, $v) = @_;

  $this->{'size'} -= $v;
  return $this;
}

sub add {
  my ($this, $v) = @_;

  $this->{'size'} += $v;
  return $this;
}

sub toString {
  my ($this) = @_;

  return "Summary " . $this->{'size'};
}

Monday, November 24, 2008

Event driven programming with Perl

By using hash table and function pointers you can implement an event dispatcher in Perl. With this programming style you can reduce conditions statements like if-else and switch.

#!/usr/bin/perl -w
use strict;

die "Syntax: test.pl action data\n" unless @ARGV > 1;

my %handlers;

$handlers{"up"} = \&OnUpper;
$handlers{"lo"} = \&OnLower;

die "Invalid ation!\n" unless exists $handlers{$ARGV[0]};

# The dispatcher
$handlers{$ARGV[0]}->($ARGV[1]);

sub OnUpper
{
  my $param = shift;
  print(uc "$param\n");
}

sub OnLower
{
  my $param = shift;
  print(lc "$param\n");
}

Saturday, November 22, 2008

Configure IPFW

IPFirewall is the default firewall for Mac OSX and FreeBSD. Use the ipfw command tool to define firewall rules for your computer.

This shell script creates my firewall rules when I am using insecure networks in my professional work. The script configuring firewall logging and create rules to block traffic on network all interfaces except loopback interface and outbound traffic for HTTP, HTTPS, SSH, SMTP, NTP and DNS. 

#!/bin/sh

sudo ipfw -q flush

if [ "$1" = "on" ]; then
  sudo sysctl -w net.inet.ip.fw.verbose=2 > /dev/null
  sudo ipfw -q add allow ip from me to any via lo0

  sudo ipfw -q add allow tcp from me to any 80 keep-state out
  sudo ipfw -q add allow tcp from me to any 443 keep-state out
  sudo ipfw -q add allow tcp from me to any 22 keep-state out
  sudo ipfw -q add allow tcp from me to any 993 keep-state out
  sudo ipfw -q add allow tcp from me to any 25 keep-state out

  sudo ipfw -q add allow udp from me to any 123 keep-state out
  sudo ipfw -q add allow udp from me to any 53 keep-state out
  sudo ipfw -q add deny log all from any to any
  echo "Firewall is activated"
else
  sudo sysctl -w net.inet.ip.fw.verbose=0 > /dev/null
  echo "Firewall is disabled"
fi

Saturday, October 25, 2008

Integrate Growl with syslog

Growl is a great notification system for Mac OS X. Integrating Growl is easy, you only have to write a small perl script and reconfigure the syslog system.

syslog.conf
*.notice;authpriv.none;kern.debug;    |exec /bin/growl_log.pl

Perl script
#!/usr/bin/perl
use strict;
use Net::Growl;

my $host = "0.0.0.0"; // Your Apple computer
my $app = "Syslog Integrator";
my $pwd = "xyz123";

Net::Growl::register(host => $host, application => $app, password => $pwd) ;

my $log = `tail -n 1 /var/log/messages`;

Net::Growl::notify(host => $host, application => $app, password => $pwd, title => "Syslog", description => $log);

exit 0;

For more information about Growl, click here.

Saturday, October 11, 2008

Turbo C

Borland Turbo C was my first serious attempt to be an software developer. Earlier I have tried to create computer software with Borland Turbo Pascal with various success.

After a few month I discovered the only limit is your imagination, not the development tool. This knowledge is a "silver bullet" for my professional work today. 

Saturday, October 4, 2008

Powered by FreeBSD 7.0

When I installed a new hard disc drive after a hardware failure on the server, I decided to use FreeBSD version 7.0 instead of Debian GNU/Linux. Like other Unix systems, FreeBSD is a complex, advanced and extremely robust operating system.

Friday, October 3, 2008

Use Perl to Base64 encode and decode files

#!/usr/bin/perl
use MIME::Base64;

# Read entire file at once
local($/) = undef;

if($ARGV[0] eq "enc") {
  print encode_base64(<STDIN>);
}
else {
  print decode_base64(<STDIN>);
}

Sunday, August 10, 2008

Toshiba T1000

My first computer was Toshiba T1000 with Intel 8088 4.77 MHz, 512 kbytes RAM and MS-DOS 2.11.

Friday, August 8, 2008

SAGA

My first rock concert was SAGA from Canada at the Stockholm Hovet in beginning of 1980's. At that time, I didn't know anything about computer hardware or software. My interest for computers and software engineering started a few years later.

Sunday, February 3, 2008

Perl Scripts

Writing Perl scripts are a fun and easy way to automate complex processes.

This simple script downloads text files over network using HTTP protocol and could be used to automate test processes for web applications.

#!/usr/bin/perl
use IO::Socket;

die "Syntax: wget.pl uri\n" unless @ARGV > 0;

($schema,$host, $path) = split("[://]+", $ARGV[0], 3);

$sock = new IO::Socket::INET (PeerAddr => $host,
PeerPort => '80',
Proto => 'tcp');

die "$host is down\n" unless $sock;

print $sock "GET /$path HTTP/1.1\n";
print $sock "Host: ", $host, "\n";
print $sock "Connection: ", "close\n\n";

while ($data = <$sock>) {
  print $data;
}

Wednesday, January 2, 2008

Regular expression

Regular expression is a powerful technique for non-beginners to validate, replace or split text values. Use tools like RegExpress to test and learn regular expression syntax.

Validate a simple e-mail address.
Syntax: ^[a-z.]+@[a-z]+(\.+[a-z]+)+
^Matches the start of the string
[a-z.]+ Allow one or more lower case char a to z and dot
@Must contain one e-mail At character
[a-z]+Allow one or more lower case char a to z
(Begin sub expression
\.Must contain one dot
[a-z]Allow one or more lower case char a to z
)End sub expression
+One or more sub expression


Split one or more email addresses separated by comma or semicolon.
Syntax: [,;]+

[,;]Find separator comma or semicolon
+One or more separator