elmak elmak - 1 month ago 4
Perl Question

perl use variable under a pattern regex

How to use variable in the pattern ?

Please I want to this :

my $project="SDK" //or something that i will get it after calling some function.
my $JIRA_regex = '(^| )($project)-(\d+)';
print "pattern = $JIRA_regex\n";


Output is not good :

(^| )(${project})-(\d+)

Answer

Single quotes don't interpolate variables; double quotes do.

my $project = "SDK"; # or whatever
my $JIRA_regex = "(^| )($project)-(\\d+)";
print "pattern = $JIRA_regex\n";

(Note that I had to escape the backslash to get a literal \d into the string.)

There are some other things to consider:

  • Is $project supposed to be interpreted as a regex? (Probably not, in which case it should be wrapped in \Q \E or quotemeta().)
  • Does $JIRA_regex have to be a plain string? If not, it's easier to make it a regex object.

In which case a better solution would be:

my $project = "SDK"; # or whatever
my $JIRA_regex = qr/(^| )(\Q$project\E)-(\d+)/;
print "pattern = $JIRA_regex\n";