Monday, November 30, 2009

Perl - A compact multiple-value IF statement using grep

Here is a simple way to compare multiple string values against a variable.
Normally one might use multiple OR conditions such as:

$pet = "rabbit";
if ( uc($pet) eq "CAT" || 
     uc($pet) eq "DOG" ||
     uc($pet) eq "HAMSTER" ||
     uc($pet) eq "RABBIT" ||
     uc($pet) eq "RACCOON" ||
     uc($pet) eq "MONKEY" ||
     uc($pet) eq "HORSE" ) {
     printf("A %s is a Mammal.\n", ucfirst($pet) );
}
elsif ( uc($pet) eq "ALLIGATOR" ||
        uc($pet) eq "FROG" ||
        uc($pet) eq "SALAMANDER" ||
        uc($pet) eq "SNAKE" ||
        uc($pet) eq "TOAD" ) {
    printf("A %s is an Amphibian.\n", ucfirst($pet) );
}
else {
    printf("What is a %s ?\n", ucfirst($pet) );
}


Here is an easier way (Full string match, not case-sensitive):

#Search word
$pet = "rabbit";

#Regular Expression: / ^=beginning of string, $pet variable, $=end of string / i=ignore case
#Using Anonomous Array:  ("cat", "dog", "...as-many-as-you-like...", "horse")
if ( grep /^$pet$/i, ("cat","dog","hamster","RABBIT","Raccoon","Monkey","horse") ) {
    printf("A %s is a Mammal.\n", ucfirst($pet) );
} 
elsif ( grep /^$pet$/i, ("Alligator", "frog", "salamander", "Snake", "toad") ) {
    printf("A %s is an Amphibian.\n", ucfirst($pet) );
}
else {
    printf("What is a %s ?\n", ucfirst($pet) );
}


Some notes:
  • Removing the "i" option would make the statement case-sensitive:
  • Altering the Regular Expression slightly, will match the beginning or end of strings.
    Matching the beginning of the strings (remove the ending $ symbol):
    Matching the end of the strings (remove the leading ^ carret symbol):

Sunday, November 22, 2009

AWK - Sort lines from shortest to longest

Display filenames in a directory with the shortest filenames first and longest length last:

ls -1 | awk '{printf "%d\t%s\n", length($0), $0}' | sort +0n -1 | sed 's/^[0-9][0-9]* //'

Perl One-liners - An easy way to begin using Perl

A Perl one-liner is a small perl script run from the command-line prompt or a shell script as one command. You can pack a lot of power in a small command. By embedding Perl into a shell script you can enhance the capabilities of your shell script a great deal.

Here are some examples:

Fixed Length Data File - Show records where a column range matches a given string.

General Command:


perl -ne 'print if substr($_, StartCol, Stringlen) =~ "searchstring";'  infile.txt > outfile.txt


Example: Find records where position 488-489 is equal to "CA". Keep in mind that for startcol, the first character of the record begins a position 0.


perl -ne 'print if substr($_, 487, 2) =~ "CA";' infile.txt > outfile.txt

Pipe-Delimited Data File - Show records where a column 2 value equals 2

123|2|Oak
456|4|Cedar
789|2|Willow

perl -ne 'split(/\|/); @line=@_; print if $line[1] == 2;' in.txt > out.txt

Korn shell - Embed Perl for loop inside Korn shell for loop

Example: Loop to count from 1 to 99 (by Odd numbers)
Note: everything between $( ... )  is the perl one-liner

for i in $(perl -e 'for ($i=1; $i<100; $i+=2) {print "$i\n";}')
do
  echo $i
done

Frequency Counter - Pipe Standard Input into this one-liner File of votes with a name on each line - in.txt

cat in.txt | perl -e '%freq;while (<>) {chomp;$freq{$_}++;} printf("%-40s %10i\n", $_, $freq{$_}) foreach sort keys %freq;'

Output:
Al               3
Fred           5
Mary         6

Tuesday, November 17, 2009

ActiveState Perl on Windows - get Date and Time into variables

Places date and time into variables to be used later.

$dt = system("date /T 2>NUL");
chop $dt;
$tm = system("time /T 2>NUL");
chop $tm;