countdown

This small script is an alternative to sleep(1) that gives a visual clue to the user about the remaining seconds in the delay

#!/usr/bin/perl
$|++;

my $secs = shift;
die("Usage: $0 <secs>\n") unless (defined $secs) && ($secs>=0);
while($secs>0) {
        printf("\r% 4d", $secs);
        sleep 1;
        --$secs;
}
print "Done          \n";

(Download)
There are numerous instances where you might want your shell scripts to sleep(1) giving the user a clue about what’s going on, but just to relate to a previous example, let’s see how this can be used to throttle file leeching:

$ for i in `count 1 10 %02d`; do wget http://..../file-$i.pdf; countdown 30; done

Anansi Boys

Anansi BoysIt took a bit longer than I originally expected, but last night I finally finished reading Anansi Boys and I just have this to say: Neil Gaiman is a master storyteller.
Neil has just weaved a great story from a few seemingly loose strands in American Gods and -I swear- it is a solid web that he traps the reader into. The characters are solid and well developed over time, and by the end of the book they jump right off the page. The situations are very well constructed and some scenes have a frail, dreamlike quality. I can certainly relate to some aspects of the situations that Fat Charlie goes through, most certainly to those bits about parents being involuntarily embarrasing entities. As it is written, the characters’ ultimate destinies are very much like melodies that intertwine gradually and evolve into a great, powerful song. This song flows naturally, armonically, unavoidably. The musical bridges are in their right place, and in retrospect I can see that every note is there for a reason. The end resonates loudly, like a sustained note in a song I that I feel that I’ve heard before. And I probably have: Even now, Neil is one of the few authors that has the strange gift of haunting my sleep with their stories.
Neil: while you’re conceivably baking in the sun and healing from that nasty cold in some heavenly island in the Caribbean after which you shaped St. Andrews, I just have to thank you for taking me wide awake to that mysterious land at the beginning of time that we ordinary humans only visit in our sleep.

count

count is a minimalist perl script in the spirit of seq(1) but with a simpler syntax. It only counts in increments of 1, but -on the other hand- it knows how to count down.

#!/usr/bin/perl
use strict;
my($from,$to,$fmt,$inc)=@ARGV;
$to||=$from;
$fmt||="%d";
print join("\n",map{sprintf("$fmt",$_)}($from>$to?reverse($to..$from):($from..$to))),"\n";

(Download)
For instance, “count 10 1 %03d” will count down from 10 to 0 padding with zeroes to three digits. “count 0 15 %x” will count in hex. If you omit the format string it will default to “%d” (decimal, no padding).
count is very useful -among other things- for file leeching:

$ for i in `count 1 10 %02d`; do wget http://..../file-$i.pdf; done

de64

Base64 is used to encode binary data in printable ASCII form. de64 is a trivial perl script to decode such strings:

#!/usr/bin/perl
use MIME::Base64;
local $/ = undef;
print decode_base64(shift||<STDIN>);

(Download)
One application of de64 is decoding UTF8 LDAP attributes inside LDIF files. For instance, “cn:: Um9iZXJ0byBNYXJ0w61uZXo=” may be decoded with

$ de64 Um9iZXJ0byBNYXJ0w61uZXo=
Roberto Martí­nez

(Look Randal! I’m using a CPAN module this time! ;-) ) Of course, all the heavy lifting is done by MIME::Base64 from CPAN.

Luhn algorithm in PHP

As I mentioned before, the Luhn algorithm is used to validate some interesting numbers, most notably GSM IMEIs and credit card numbers. Here’s another implementation I wrote, this time in PHP.

	function luhn($str) {
		$odd = !strlen($str)%2;
		$sum = 0;
		for($i=0;$i<strlen($str);++$i) {
			$n=0+$str&#91;$i&#93;;
			$odd=!$odd;
			if($odd) {
				$sum+=$n;
			} else {
				$x=2*$n;
				$sum+=$x>9?$x-9:$x;
			}
		}
		return(($sum%10)==0);
	}

(Download)

perlwhich

Are you wondering where the heck does some arcane module come from? Wonder no more, perlwhich comes to the rescue:

#!/usr/bin/perl
use strict;
use File::Spec;

my $module = shift @ARGV;
$module=~s,\.,,igs;
my $pm=$module.'.pm';
my @path = split(/::/,$pm);
my $found = 0;
foreach my $dir (@INC) {
        my $file = File::Spec->catfile($dir,@path);
        if(-f $file) {
                print $file,"\n";
                $found=1;
        }
}
exit(!$found);

(Download)
Next time you need to know some module’s path just run it like this:

$ perlwhich Data::Dumper
/usr/lib/perl/5.8/Data/Dumper.pm

If a module resides in multiple locations under @INC, perlwhich will let you know as well:

$ perlwhich Salesforce
/usr/local/lib/site_perl/Salesforce.pm
/usr/local/share/perl/5.8.4/Salesforce.pm

Luhn algorithm in Perl

Here’s an implementation of the Luhn algorithm in perl.

#!/usr/bin/perl
use strict;
my $number = shift(@ARGV) || die("Usage: $0 <number>\n");
$number=~s,[^0-9],,g;
my($sum,$odd);
foreach my $n (split(//,$number)) {
        $odd=!$odd;
        if($odd) {
                $sum+=$n;
        } else {
                my $x=2*$n;
                $sum+=$x>9?$x-9:$x;
        }
}
my $ok = 0+(($sum%10)==0);
exit(($sum%10)!=0);

(Download)

This program was designed for shell scripting, using something like

$ if ./luhn 457623486; then echo "ok"; else echo "error"; fi
ok

but it should be trivial to modify it for other purposes.
I’m using this algorithm to validate GSM IMEI numbers, but the Luhn algorithm is also behind credit card numbers.

Phonetize

A small filter to phonetize STDIN into the NATO phonetic alphabet. It’s very useful to spell passwords over the phone.

#!/usr/bin/perl
use strict;
my %ALPHA = map {uc(substr($_,0,1))=>$_} qw( Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike November Oscar Papa Quebec Romeo Sierra Tango Uniform Victor Whiskey X-ray Yankee Zulu );
while(<STDIN>) {
        chomp;
        print $_, "\n";
        print join(' ',map {$ALPHA{uc($_)}||$_} (split(//,$_))),"\n";
}

Here’s the source code.
Yup, I know about Lingua::Alphabet::Phonetic::NATO but I needed a quick script without module dependencies. Yes, I haven’t been able to learn the NATO phonetic alphabet yet -unlike some geeks with too much time in their hands (you know who you are)- and yes, I know I’m lazy, but that’s why I am a perl fan anyway ;-) .
There’s more information about this alphabet atWikipedia. You migth want to donate a few bucks while you’re there.