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: 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: 3306
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:


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)


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


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

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