in reply to hex code passed from command line is interpreted literally in substitution

Perhaps you're taking the wrong approach. If you want to take command line arguments and use them as parameters in an s/// statement, why not simply let the user enter the s/// statement as a whole? All you have to do is eval it.

If you have to call it often (thousands of times), you can simply wrap it in a sub to compile it. $_ can simply represent the sub's parameter.

my $perl = shift; $code = eval "sub { local \$_ = shift; $perl; return $_ }" or die "Syntax error: $@"; foreach my $var (@lots_of_data) { $var = $code->($var) }

And in the end, you give the user the option to pass in other code than just a simple s///. This is something that the module File::Rename does, for example, a command line utility to rename files where you can define how the file name should be named in a Perl snippet that changes the value of $_ (the file name).

Replies are listed 'Best First'.
Re^2: hex code passed from command line is interpreted literally in substitution
by Allasso (Monk) on Mar 06, 2011 at 00:03 UTC
    Actually, it is only the RHS that the user is passing. I mislead you because of my example. I only used that because of my curiosity as to why it worked on one side but not the other.

    The pattern to be replaced is provided by the script, ie, the script searches for illegal character sequences and interactively replaces them with the user's input.

    What I came up with by the direction of others here seems to work fine. I'm happy so far.
Re^2: hex code passed from command line is interpreted literally in substitution
by Allasso (Monk) on Mar 09, 2011 at 22:39 UTC
    well the method I mentioned fell apart when trying to pass $1, $2 etc to be interpolated as captures, so you and ikegami are right, it really needs an eval. I did want to stick with the script 'pattern' 'replacement' format however (rather than script 's/pattern/replacement/') so I used this instead:
    #!/usr/bin/perl -wl use strict; my ($arg_1, $arg_2) = @ARGV; $_ = "apples"; my $expr = "s/".$arg_1."/".$arg_2."/"; eval $expr; print; ------- ./test.pl '\x61(.*)\x73' '\x41$1\x53' AppleS
      Now give your program these magic arguments "destroyer" "`rm -rf \x2f `"
        Yeah, so it replaces the string "destroyer" with the string "`rm -rf \x2f `". So what?