Four very identical regular expressions. I am replacing the strings with the following scalar values. How can this be more efficient?
$line =~ s/\[(receiver)\]/$receiver/g;
$line =~ s/\[(place)\]/$place/g;
$line =~ s/\[(position)\]/$position/g;
$line =~ s/\[(company)\]/$company/g;
Thank you.
to combine two expressions or more, put every expression in brackets, and use: *?
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
Consider just using a real templating system. Template Toolkit for instance is very easy.
Leaving that aside, you say you want it more efficient. Is its current perceived inefficiency a problem? If not, leave it alone.
You could do it all in one pass:
my %subst = (
'receiver' => $receiver,
'place' => $place,
'position' => $position,
'company' => $company,
);
$line =~ s/\[(receiver|place|position|company)\]/$subst{$1}/g;
but this will act differently if, for instance, $receiver
is 'place'.
Ok, let's see, what you want:
if you want to 'evaluate' the value of variable, that name you found in the string, then, you need:
my $receiver = 'rcv';
my $place = 'plc';
my $position = 'pstn';
my $company = 'cmpn';
my $allVariableNames = join('|',qw(receiver place position company));
$line = '[receiver]';
$line =~ s/\[($allVariableNames)\]/'$'.$1/eg;
#$line =~ s/\[($allVariableNames)\]/eval('$'.$1)/eg; <- smarter and shorter variant
print $line,"\n"; #contain $receiver
print eval($line), "\n"; # evaluate ($receiver) => get rcv
it is another way to do this task, see ysth' answer above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With