[Melbourne-pm] problems passing arguments to s{}{}

Geoff Crompton geoff.crompton at strategicdata.com.au
Wed Aug 9 23:39:24 PDT 2006


Hi All,

I am having a problem using a parameter to a function as part of a s///
operation. Consider the following code that demonstates the problem I'm
having:

use strict;
use warnings;

replace_string('source $HOME/homeconfig/muttrc', q{$HOME});

sub replace_string {
    my ($sourced_string, $homedir_shortcut ) = @_;

    $sourced_string =~ s{$homedir_shortcut}{$ENV{HOME}};
    print "sourced_string is now $sourced_string\n";

    #do some processing

    $sourced_string =~ s{$ENV{HOME}}{$homedir_shortcut};
    print "sourced_string is now $sourced_string\n";
}


The output I get is:
$ perl perltest
sourced_string is now source $HOME/homeconfig/muttrc
sourced_string is now source $HOME/homeconfig/muttrc

The output I would like is:
$ perl perltest
sourced_string is now source /home/geoffc/homeconfig/muttrc
sourced_string is now source $HOME/homeconfig/muttrc

The problem is that passing '$HOME' in to the regular expression means
it tries to match something on the end of the incoming string in the
first s{}{}, which fails.

If I try and pass in '\$HOME' like:

replace_string('source $HOME/homeconfig/muttrc', q{\$HOME});

Then I get the output:
$ perl perltest
sourced_string is now source /home/geoffc/homeconfig/muttrc
sourced_string is now source \$HOME/homeconfig/muttrc

And I can't just keep a copy of sourced_string to reinstate, because the
actual program I'm trying to write uses the two s{}{} operators in
different ways, and it's not actually the same sourced_string.

Am I going to have to resort to some contortions with index(), substr()
and the like? Or should I preprocess $homedir_shortcut in
replace_string() to escape any inadvertent regular expression markup
(and is their a perlmod to do that)?

-- 
Geoff Crompton
Debian System Administrator
Strategic Data
+61 3 9340 9000


More information about the Melbourne-pm mailing list