Sunday, December 14, 2008

Recipe - Do Something To Each File In Directory

This one is a real life-saver!

To do the same operation on each file, in Windows, you can use the for command.
for /F %i in ('dir *.dbg /s/b ') do @del %i

The above example deletes all *.dbg files under the current directory

Explanation
for /F %i ......... for each %i
in('dir *.dbg /s/b ') ..... in the list returned by the command. dir /s specifies a recursive search, /b causes it to to output just a list, without the file details
do @del %i ...... del %i is the command to delete the file. @ suppresses the display of the command

Recipe Syntax
for /F {%var} in ('{list-builder-command}') do {action-command}

Tuesday, November 11, 2008

Digital Peer

Found a really cool and useful site while browsing around
http://www.digitalpeer.com/

There are tips, tutorials and articles here.

Hope it stays online!

Saturday, July 26, 2008

On Reviews

Reviews are like makeup; they can't make you beautiful, only less ugly.
- TJ

Monday, January 28, 2008

Perly Gates

Tip 1:
Replacing string content with another string when both could contain backslashes.


Explanation:
Basically, you have to use \Q to escape. Otherwise, the contents of the strings (search & replace strings) will be interpreted as escape sequences.

Example:
The following is an extract from a script to get the relative path of a file with respect to a base-directory.

#!/usr/bin/perl

$BASE = "d:\source\";
print "
Base : $BASE\n";

$TARGET = "
d:\source\temp\test.txt";
print "
Original : $TARGET\n";


$TARGET =~ s/\Q$BASE//;
#Replacing with null string
#syntax for replace:
#TargetString =~ is s/SearchString/ReplaceString/

print "
Modified : $TARGET\n";
#Target becomes "
temp\test.txt"


Tip 2:
Replace backslashes with forward slash.

If you do this the regular way, the regex you write will likely look like a squiggly drawing :) Something like /\/\\/ ;), which is a pain to read or debug.

#!/usr/bin/perl
# In Perl, any character can be used to delimit the regex! Here, using @ as separator
$STRING =~ s@\\@/@g;


Yeah, it's still ugly and we need to escape the backslash as \\, but that's they way it goes. Use this tip whenever you need to replace

Tip 3:
Get command line output into a variable


Here's a function to do this. Takes two parameters, the command-string to execute and a boolean option for showing the output on the display.

sub getCommandOutput
{

my ($COMMAND, $DISPLAYOUTPUT) = @_;

open(COMMAND_OUTPUT, "$COMMAND 2 >&1 |");
my @OUTPUTLINES = <COMMAND_OUTPUT>;
chomp(@OUTPUTLINES);
close(COMMAND_OUTPUT);

foreach $OUTPUTLINE(@OUTPUTLINES){

print "\n$OUTPUTLINE" if $DISPLAYOUTPUT;
}

print("\n") if ($DISPLAYOUTPUT);
return @OUTPUTLINES;

}


# TODO You may want to capture the error stream separately

The function returns the output of the command as an array which you can store into a variable.