Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference in Perl when passing a variable in a regular expression between using $variable and ${variable}

I am reviewing some ClearCase triggers written in Perl. I have noticed that in some regular expressions, variables are passed either straighforwardly or with their names in curly brackets.

For example, I have the following line of code in a trigger:

if ($baseline !~ /^${component}_(|.*_)$phase\.\d+(|[a-z]|-\d+|${automateddigit})$/ &&
        $baseline !~ /^${project_root}_$phase\.\d+(|[a-z]|-\d+|${automateddigit})$/)

$component, $phase, $automateddigit, $project_root are all variables.

Why are some passed as $variable and other passed as ${variable} in the regular expression?

Does it come from how they are initialised?

Here are the line of code initialising them:

($project = $ENV{CLEARCASE_PROJECT}) =~ s/\@.*$//;
($component = $ENV{CLEARCASE_COMPONENT}) =~ s/\@.*$//;

($project_root, $phase) = ($project =~ /^(.*)_(R\d+.*)$/);

exit(0) if (! $phase);

$phase .= ".0" if ($phase =~ /^R\d+$/);

$automateddigit = '';

$istream = `cleartool desc -fmt "%[istream]p" project:$ENV{CLEARCASE_PROJECT}`;

$componentlist = `cleartool desc -fmt "%[components]Cp" stream:$ENV{CLEARCASE_STREAM}`;
$componentsnbr = split(',', $componentlist);

if ($componentsnbr > 1) {
    $automateddigit .= '\\.\\d+';
}
like image 382
Thomas Corriol Avatar asked May 01 '09 10:05

Thomas Corriol


People also ask

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".

What does %s mean in Perl?

Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.

How do I match a variable in Perl?

Perl makes it easy for you to extract parts of the string that match by using parentheses () around any data in the regular expression. For each set of capturing parentheses, Perl populates the matches into the special variables $1 , $2 , $3 and so on. Perl populates those special only when the matches succeed.


1 Answers

If you pass the variable as ${name}, this explicitly delimits where the end of the variable name is, and where the rest of the quoted string begins. For example, in your code:

if ($baseline !~ /^${component}_(|.*_)$phase\.\d+(|[a-z]|-\d+|${automateddigit})$/ &&

Without the {} delimiters:

if ($baseline !~ /^$component_(|.*_)$phase\.\d+(|[a-z]|-\d+|${automateddigit})$/ &&

Note that the variable $component (you can refer to it either way) will be misinterpreted as $component_ because of the trailing underscore in the regular expression.

like image 128
1800 INFORMATION Avatar answered Sep 22 '22 06:09

1800 INFORMATION