Richard
Richard

Reputation: 3100

Perldoc variable syntax: $foo vs ${foo}

I was just browsing the perldocs when I came across this in an example ( http://perldoc.perl.org/perlre.html#Regular-Expressions - see Capture Groups example )

"aa" =~ /${a}/; # True
"aa" =~ /${b}/; # True
"aa0" =~ /${a}0/; # False!
"aa0" =~ /${b}0/; # True
"aa\x08" =~ /${a}0/; # True!
"aa\x08" =~ /${b}0/; # False

I couldn't find any documentation on what that syntax means.

So what does the regex /${a}/ mean in this context?

Upvotes: 3

Views: 184

Answers (2)

Jens
Jens

Reputation: 72697

The braces are needed to disambiguate $a from $a0. Note that the tokenizer is greedy, so a variable name is the longest sequence possible. If in a variable interpolation another alphabetic or number follows, you need the ${name} syntax.

Upvotes: 3

$ with brackets avoid the ambiguity of variable names. Such that:

$foo = 'house';
'housecat' =~ /$foo/;      # matches
'cathouse' =~ /cat$foo/;   # matches
'housecat' =~ /${foo}cat/; # matches

Also in the link that you have given, there is a definition for $a and $b, but you have forgotten to copy here.

Upvotes: 2

Related Questions