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.




No comments: