in reply to Re^3: Regex stored in a scalar
in thread Regex stored in a scalar

I can't see how to enter that with my $subst = <STDIN>;
True, it won't work this way ... it might be feasible with a slight syntax tweak and one further step to process it ... assumes that you know ... you might need some newline characters to be reprocessed

As long as you can get  \nything into a scalar, you can search/replace with it, and a statement like
    my $subst = <STDIN>;
is perfectly adequate to capture any sequence with a literal backslash in it:

c:\@Work\Perl>perl -wMstrict -e "print 'enter a string: '; my $string = <STDIN>; chomp $string; print qq{'$string' \n}; " enter a string: )\n( ')\n('
(Caveat: Actually, I can only test this under Windoze; there may be OSen that mung backslashes in situations like this.)

Once you have captured a string with a backslash, you can use it for search/replace straightforwardly:

c:\@Work\Perl>perl -wMstrict -le "printf 'enter search regex: '; my $search = <STDIN>; chomp $search; ;; printf 'enter replacement string: '; my $replace = <STDIN>; chomp $replace; ;; print qq{doing s/$search/$replace/}; ;; my $s = qq{as\ngh\njk}; printf qq{%*s: '$s' \n}, 7, 'initial'; ;; my @regex = ( { lh => $search, rh => $replace, }, ); ;; for my $hr_s (@regex) { $s =~ s[ (?-x)$hr_s->{lh}]{ qq{qq{$hr_s->{rh}}} }xmsgee; } ;; printf qq{%*s: '$s' \n}, 7, 'final'; " enter search regex: \n enter replacement string: __\n__ doing s/\n/__\n__/ initial: 'as gh jk' final: 'as__ __gh__ __jk'
(This is essentially the example code from below.)


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
Re^5: Regex stored in a scalar
by Laurent_R (Canon) on Aug 22, 2015 at 18:53 UTC
    Agreed, but my only point was that, under Unix, if you enter "foo\n" at STDIN or at the command line, the backslash is lost and you get "foon" into your variable. So I needed to put two backslashes, meaning that I then needed to change from the string "\\n" to the newline character "\n" to get the replacement string "foo\n" I was looking for. There might be a better way, but at least I was showing that this was possible.

    So, in effect, we are saying almost the same thing, I believe.

    Escaping and quoting rules are not exactly identical in Perl and in Unix (and also not under Windows), so it can get a bit contrived (and not portable) exactly to get what you want.