How to trim a Perl string by escaping the replacement string in s /// when reading from a file?

This question is similar to my last , with one difference to make the toy script look more like my actual one.

Here is a toy script, replace.pl ( Edit: now with 'use strict;', etc.)

#! /usr/bin/perl -w

use strict;

open(REPL, "<", $ARGV[0]) or die "Couldn't open $ARGV[0]: $!!";
my %replacements;
while(<REPL>) {
   chomp;
   my ($orig, $new, @rest) = split /,/;
   # Processing+sanitizing of orig/new here
   $replacements{$orig} = $new;
}
close(REPL) or die "Couldn't close '$ARGV[0]': $!";

print "Performing the following replacements\n";
while(my ($k,$v) = each %replacements) {
   print "\t$k => $v\n";
}

open(IN, "<", $ARGV[1]) or die "Couldn't open $ARGV[1]: $!!";
while ( <IN> ) {
   while(my ($k,$v) = each %replacements) {
      s/$k/$v/gee;
   }
   print;
}
close(IN) or die "Couldn't close '$ARGV[1]': $!";

So, now let's say that I have two files: replacements.txt (using the best answer from the last question, plus a replacement pair that doesn't use substitution):

(f)oo,q($1."ar")
cat,hacker

and test.txt:

foo
cat

When I run perl replace.pl replacements.txt test.txt, I need a conclusion

far
hacker

'$1."ar"' ( ), , ( ). foo ar, cat/hacker eval'd . .

, replace.pl / replacements.txt? replacements.txt, ( , ).

, , .

0
3

, , . , , , .

, 3 open, . . , perlstyle (. http://perldoc.perl.org/perlstyle.html ) $!.

, , , q ($ 1. "ar" ). $1. "Ar". q(), . . , script script.

script :

#! /usr/bin/perl -w
use strict;

open(REPL, "<", $ARGV[0]) or die "Couldn't open '$ARGV[0]': $!!";
my %replacements;
while(<REPL>) {
   chomp;
   my ($orig, $new) = split /,/;
   # Processing+sanitizing of orig/new here
   $replacements{$orig} = '"' . $new . '"';
}
close(REPL) or die "Couldn't close '$ARGV[0]': $!";

print "Performing the following replacements\n";
while(my ($k,$v) = each %replacements) {
   print "\t$k => $v\n";
}

open(IN, "<", $ARGV[1]) or die "Couldn't open '$ARGV[1]': $!!";
while ( <IN> ) {
   while(my($k,$v) = each %replacements) {
      s/$k/$v/gee;
   }
   print;
}
close(IN) or die "Couldn't close '$ARGV[1]': $!";

replacements.txt:

(f)oo,${1}ar
cat,hacker
+4

. :

  • "e"

     
    s/$k/$v/geee;    # eeek
  • replacements.txt,

     
    (f)oo,$1."ar"
0

q() ;

 (f)oo,$1."ar"
($k,$v) = split /,/, $_;

: ,

 (f)oo,"${1}ar"

, . s///.

@drhorrible, , .

use strict;use warnings;

my $str = "foo";
my $repl = '(f)oo,q(${1}."ar")';
my ($k,$v) = split /,/, $repl;
$str =~ s/$k/$v/gee;
print $str,"\n";

$str = "foo";
$repl = '(f)oo,$1."ar"';
($k,$v) = split /,/, $repl;
$str =~ s/$k/$v/gee;
print $str,"\n";

$str = "foo";
$repl = '(f)oo,"${1}ar"';
($k,$v) = split /,/, $repl;
$str =~ s/$k/$v/gee;
print $str,"\n";

:
${1}."ar"
far
far

0

Source: https://habr.com/ru/post/1789621/


All Articles