CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
How Do I Use a regex back-reference in a Command Line Argument?

 



ferulebezel
New User

Nov 29, 2009, 1:15 AM

Post #1 of 2 (3399 views)
How Do I Use a regex back-reference in a Command Line Argument? Can't Post

I'd like to do a search and replace on a bunch of filenames using regex values that are passed to the script from the command line argument which meand that the $1 or \1 will be in a string that I will be using in the regex.

For example:


Code
my $regexS = $ARGV[0]; 
my $regexR = $ARGV[1];


if $_ is something like 9999.txt

and I run the script


Code
scriptname '\d\d\d\d.txt' '00$0'


the line


Code
s/$regexS/$regexR/g;


turns $_; into


Code
00$0


instead of


Code
009999.txt


What can I to to make this work?


7stud
Enthusiast

Dec 3, 2009, 1:25 PM

Post #2 of 2 (3317 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:


Code
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


=======

Code
$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)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives