Kabachok
Kabachok

Reputation: 603

Perl: how to find a match in one string and make a substitution in another?

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

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

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

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions