Hi Nora!

Welcome to Perl.

On Wednesday 24 Feb 2010 11:00:46 HACKER Nora wrote:
> Hi,
> 
> I want to apply a certain substition to a string, whereas the whole
> substitution is defined in a variable in another script. Unfortunately,
> it doesn't work as wanted :-( Looks like this:
> 
> sub.conf:
> $sub='s/db$//g';

Please add "use strict;" and "use warnings;" to your code. 

You cannot put a s/../.../ expression directly in a variable and except it to 
work on the right-hand-side (RHS) of a =~. It doesn't work that way.

> 
> script.pl:
> do sub.conf;

Why are you using "do" instead of "use" or "require"? See 
http://perl-begin.org/ for more information and recommended books and 
tutorials.

And again you should add strict and warnings.

> print "Please enter string: ";  # e.g. mydb
> $input=<STDIN>;

Normally <ARGV> - shortened to <> is preferable over <STDIN>;

> print "$sub\n";  # gives the exact string as defined in sub.conf
> (without apostrophes)
> $input=~$sub;
> print "$input\n";  # in this example should be "my"
> 
> Can anybody please tell me my mistake?

You can do one of the following:

1. Put the left-hand-part of the s/// in a qr// variable:

(Untested)
<<<
my $exp = qr{hello$};

my $string = "Time to say hello";

$string =~ s{$exp}{goodbye};
>>>

2. You can also try using the stringified eval "" (which could be error prone 
and generally not recommended.

3. You can try constructing a closure:

(Untested)
<<<

my $op = sub { my $s = shift; $s =~ s{hello$}{goodbye}; return $s; };

.
.
.

print $op->("Time to say hello"), "\n";
>>>

Regards,

        Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
"Star Trek: We, the Living Dead" - http://shlom.in/st-wtld

Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to