Reputation: 603
Lets say I have a file learning.txt with the following info :
A *
B &
C (
D )
How can I take a user-input string abc
and return *&(
Upvotes: 1
Views: 60
Reputation: 26131
There is this very efficient (O(N+M)) solution in Perl
my %replace = ( A => '*', B => '&', C => '(', D => ')' );
my $re = join '|', map quotemeta, keys %replace;
$re = qr/($re)/;
# and somewhere else in the scope with $re and %replace
s/$re/$replace{$1}/g;
And but for the case insensitive it's a little bit more complicated
use feature qw(fc); # since v5.16 use lc otherwise
my %replace = ( A => '*', B => '&', C => '(', D => ')' );
my $re = join '|', map quotemeta, keys %replace;
$re = qr/($re)/i;
my %replace_fc;
@replace_fc{ map fc, keys %replace } = values %replace;
# and somewhere else in the scope with $re and %replace_fc
s/$re/$replace_fc{fc $1}/g;
Just feed %replace
from your file like this
while (<>) {
my ($key, $val) = split;
$replace{$key} = $val;
}
Upvotes: 1
Reputation: 627488
Use /^(A|B|C)\\b\\s*(.+)/m
regex (that has a multiline option) and then concatenate second groups.
See example of this regex output here.
Upvotes: 0