-2

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+)

Thank you :)

1 - Yes I want to use $project, as string value to match or a regex too:

2 - $JIRA_regex will be matched further on the code.

This is my code that it works fine now :

my $repo=$ARGV[0];
my $comment=$ARGV[1];

my $project_pattern="[A-Z]{2,5}";

if ($repo =~ "test1.git" or $repo =~ "test2.git")
{
    $project_pattern = "\QSDK\E";
}

my $JIRA_regex = "(^| )($project_pattern)-(\\d+)";

if ( $comment =~ /$JIRA_regex/m )
{
    print "matched $2-$3\n";
}
else
{
    print "not matched\n";
}
1

1 Answer 1

4

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.