July 2010 Archives

fork'ing your world

The fork function is a very powerful tool used among many languages. Unfortunately It's not that common among Perl scripts, maybe because most scripts don't really have a need for it. But it's a handy trick to keep inside your hat.

Fork creates a new process running the same program, usually the process that calls the fork is named the parent process, and the created process is named the child process. The fork function returns 0 to the child process, and the newly created process pid to the parent. Using fork can be as simple as:

print "($$) hello\n";
my $pid = fork;
if ($p…

Watching directories for new files

Linux::Inotify2 is great for detecting newly created files in a directory. You can watch a directory by simply using:

use Linux::Inotify2;

my $inotify = new Linux::Inotify2;

$inotify->watch($dir, IN_CREATE, \&handle_new);

sub watch_new {
my $e = shift;

print "New file or dir: " . $e->fullname . "\n";
}

This will execute the callback function hande_new everytime a file is created in $dir. The function will simply…

one liner history command counter

Wondering what commands you use the most, try this one liner:

$ history | perl -ne 'END { map {print ++$i.": $_\n";} splice(@{[sort {$h{$b}<=>$h{$a}} (keys %h)]},0,5); } m/\s+\d+\s+(.*)/; $h{$1}++;'

In one of the servers I use I got:

1: ls
2: fg
3: cd ..
4: sudo tail -f /var/log/httpd/error_log
5: cd


Well, I actually added:

alias j=jobs
alias vl='sudo tail -f /var/log/httpd/error_log'


To my .bashrc after this.

Memcached to the rescue

Everyday the Internet becomes faster, and everyday new and more complex content is provided via web applications. The problem is that sometimes (maybe most of the times) these rich and complex content applications aren't fast enough to answer big flows of requests. One trick that is often used to improve throughput of slow applications is caching. Instead of always processing requests, that often require some data from one or more external sources, a possible solution is to cache the entire output to answer upcoming requests, or cache smaller components that can be used together to produce…

About smash

user-pic I blog about Perl.