Replacing string content with another string when both could contain backslashes.
Basically, you have to use \Q to escape. Otherwise, the contents of the strings (search & replace strings) will be interpreted as escape sequences.
The following is an extract from a script to get the relative path of a file with respect to a base-directory.
$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"
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.
# 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
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.
my ($COMMAND, $DISPLAYOUTPUT) = @_;
open(COMMAND_OUTPUT, "$COMMAND 2 >&1 |");
my @OUTPUTLINES = <COMMAND_OUTPUT>;
print "\n$OUTPUTLINE" if $DISPLAYOUTPUT;
print("\n") if ($DISPLAYOUTPUT);
# 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.