 |
|
Home:
Perl Programming Help:
Regular Expressions:
Re: [ferulebezel] How Do I Use a regex back-reference in a Command Line Argument?:
Edit Log
|
|

7stud
Enthusiast
Dec 3, 2009, 1:25 PM
Views: 1629
|
|
Re: [ferulebezel] How Do I Use a regex back-reference in a Command Line Argument?
|
|
|
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)
|
|
|
Edit Log:
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:26 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:27 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:29 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:30 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:33 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:34 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:35 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 1:39 PM
|
|
Post edited by 7stud
(Enthusiast) on Dec 3, 2009, 11:46 PM
|
|
|  |