
7stud
Enthusiast
Dec 3, 2009, 1:25 PM
Post #2 of 2
(1646 views)
|
|
Re: [ferulebezel] How Do I Use a regex back-reference in a Command Line Argument?
[In reply to]
|
Can't Post
|
|
I don't know what you are trying to do with $0. But I worked on your problem for a day using $1 and parentheses around part of the regex. The problem is that when perl reads a string from the command line, perl doesn't interpolate variables contained in the string. Therefore, you need to force perl to eval the replacement string in a context where $1 is visible--then perl will interpolate $1 into the replacement string. I couldn't figure out how to get eval() to do that, so I asked for help. It turns out, you can do everything inside s///, but the solution is pretty ugly. I would do it like this instead:
use strict; use warnings; use 5.010; my $str = "9999.txt"; my $pattern = shift; my $repl = shift; if ($str =~ $pattern) {#now $1 has a value my $repl = eval qq{"$repl"}; #double double quotes are needed $str =~ s/$pattern/$repl/; } say $str; --output:-- $perl 2perl.pl '(\d{4})' '00$1' 009999.txt =======
$str =~ s/$pattern/qq{"$repl"}/ee; #or $str =~ s/$pattern/eval qq{"$repl"}/e;
(This post was edited by 7stud on Dec 3, 2009, 11:46 PM)
|