First, you need to convert the text into a regex pattern. Then you need to convert the Perl program into a sh string literal.
sub text_to_shell_lit(_) {
return $_[0] if $_[0] =~ /^[a-zA-Z0-9_\-]+\z/;
my $s = $_[0];
$s =~ s/'/'\\''/g;
return "'$s'";
}
my $pat = quotemeta($hash2);
my $repl = quotemeta($hash1);
my $perl_code = 's/^'.$pat.'$/'.$repl.'/';
my $remote_cmd = join ' ', map text_to_shell_lit,
'/usr/bin/perl' => (
'-i', '-p',
'-e' => $perl_code,
'hashfile',
);
my $ssh_cmd = join ' ', map text_to_shell_lit,
'ssh' => (
'-o' => 'StrictHostKeyChecking=no',
'root@localhost',
'--',
$remote_cmd,
);
system($ssh_cmd);
That can be shortened to
sub text_to_shell_lit(_) {
return $_[0] if $_[0] =~ /^[a-zA-Z0-9_\-]+\z/;
my $s = $_[0];
$s =~ s/'/'\\''/g;
return "'$s'";
}
system(q{ssh -o StrictHostKeyChecking=no root@localhost }.text_to_shel
+l_lit(q{/usr/bin/perl -i -pe}.text_to_shell_lit("s/^\Q$pat\E\$/\Q$rep
+l\E/").q{ hashfile}));
But I wanted to present the safe but wordy version. If you do it in steps, you're more likely to get it right then if you start with this short but far more complex version.
Alternatively, you could use the multiple argument form of system instead of forming a shell command since don't need the shell.
my $pat = quotemeta($hash2);
my $repl = quotemeta($hash1);
my $perl_code = 's/^'.$pat.'$/'.$repl.'/';
my $remote_cmd = join ' ', map text_to_shell_lit,
'/usr/bin/perl' => (
'-i', '-p',
'-e' => $perl_code,
'hashfile',
);
system(
'ssh' => (
'-o' => 'StrictHostKeyChecking=no',
'root@localhost',
'--',
$remote_cmd,
),
);
By the way, I suspect sudo is a more common way of escalating to root privileges.
By the way,
s/.../.../ee
is the same as
s/.../eval "..."/e
which is very very very wrong. $hash1 does not contain Perl code to execute, so the /e is wrong, and if it was Perl code to execute, it doesn't return Perl code to execute, so the eval is wrong too.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.