braincheck() perl script

During the weekend I was getting bored, so I looked for something creative to spend time on. Since two weeks I’m using elementary OS, an Ubuntu based distribution. It was a fresh install and my notebook is currently bare. For the creative fun I installed Padre, a Perl IDE. I wrote a couple of code snippets to improve the Perl script skills.

By Sunday night I was looking like a zombie. I took a selfie (yes, I took one) using Cheese Webcam Booth, edited the same in GIMP & posted on facebook. Whoop! Whoop! A couple of minutes later ‘likes’ flowed and a cousin of mine posted that I’ve gone nuts with these programming stuffs. I quickly drafted a small program to ask myself 3 questions & check my sanity. I called it Braincheck program. I replied the facebook comments with the Braincheck code.

Is it becoming fun? Ahaan … Not yet. Fun was when Selven popped in & I know he could not resist improving the code.

The end-result was like this:

#!/usr/bin/perl
# I wrote myself this 'brain check' program.
# I'm still sane.
use strict;  
use warnings;

my $AGECHK=28;  
my $NAMECHK="ish";  
my $LOCCHK="home";  
my $TRUEMSG="Good! You're still sane.";  
my $FALSEMSG="You got something wrong buddy. Go see a doc!";

sub input{  
    my $in=;
    chomp($in);
    return $in;
}

sub braincheck{

    my ($name,$age,$location)="";
    print "What's your name? "; $name = input();
    print "How old are you? "; $age = input();
    print "Where are you right now? "; $location = input();

    if (($age !~ /^-?\d+$/) && ($age >0)) {exit 1; }

    if (($name =~ /$NAMECHK/) && ($age == $AGECHK) && ($location eq $LOCCHK))
    { print "$TRUEMSG.\n"; exit 0;}
    else { print "$FALSEMSG!\n"; exit 0;}
    exit 1;
}

braincheck();  

He stored all the static messages as variables and created an input function to obtain the answers and removing newlines. I initially did this part with several STDINs and chomps. Selven improved it by applying clean code DRY (don’t repeat yourself) principle. The same was also explained by Jochen during MSCC Clean Code presentation.

It’s great to have such folks around who constantly share the nectar of programming.


Share this post