Dynamic data within regex pattern?

D

DM

Is there a way to set up a regex substitution so that the pattern is dynamically
generated at runtime?

I.e., something along the lines of...

$output =~ s/$someVar/$someOtherVar/g;

I read in my Perl book that the replacement string is variable interpolated, but
it didn't say anything about that being the case for the regex pattern. So I
guess in the situation above, the regex would match the end of a line followed
by "someVar". And if you escaped the dollar sign, it would match "$someVar"
litterally.

Any assistance would be greatly appreciated.
 
G

Gunnar Hjalmarsson

DM said:
Is there a way to set up a regex substitution so that the pattern
is dynamically generated at runtime?

I.e., something along the lines of...

$output =~ s/$someVar/$someOtherVar/g;

What happened when you tried it?
I read in my Perl book that the replacement string is variable
interpolated, but it didn't say anything about that being the case
for the regex pattern. So I guess in the situation above, the regex
would match the end of a line followed by "someVar".

You guessed wrong.
Any assistance would be greatly appreciated.

You don't need any assistance at this stage. You need to play with
Perl, and figure out what 'works' and what doesn't. And maybe read a
little more.

Come back here if you fail in solving a particular problem.
 
P

Paul Lalli

DM said:
Is there a way to set up a regex substitution so that the pattern is
dynamically generated at runtime?

I.e., something along the lines of...

$output =~ s/$someVar/$someOtherVar/g;

I read in my Perl book that the replacement string is variable
interpolated, but it didn't say anything about that being the case for
the regex pattern.

What Perl book was that, may I ask?
So I guess in the situation above, the regex would
match the end of a line followed by "someVar".

Why just guess? Why not actually try it?
And if you escaped the
dollar sign, it would match "$someVar" litterally.

Any assistance would be greatly appreciated.

Read the section "Regexp Quote-Like Operators" from perldoc perlop.
Specifically, the paragraph beginning "PATTERN may contain variables,"

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top