I am reading O'Reilly Programming Perl, 3 rd Edition, and the text says that instead of using the ambiguous search pattern /$foo[bar]/ should use /${foo[bar]}/ so that Perl does not allow [bar] for character class. Am I missing something, or are both of these statements syntactically incorrect due to the fact that they are trying to index into an array using a string of goblins?
Yes, you missed something: bar may be a function call:
$ perl -Mstrict -E 'sub bar() { 0 } say "foo" =~ /$ARGV[bar]/ || "FAIL"' foo FAIL $ perl -Mstrict -E 'sub bar() { 0 } say "foo" =~ /${ARGV[bar]}/ || "FAIL"' foo 1 $ perl -MO=Deparse -Mstrict -E 'sub bar() { 0 } say "foo" =~ /${ARGV[bar]}/ || "FAIL"' foo sub bar () { 0 } use strict 'refs'; BEGIN { $^H{'feature_unicode'} = q(1); $^H{'feature_say'} = q(1); $^H{'feature_state'} = q(1); $^H{'feature_switch'} = q(1); } say 'foo' =~ /$ARGV[0]/ || 'FAIL'; -e syntax OK
Exact quote from the Perl Programming page , 4 th edition :
Within search patterns that also undergo double-quoted interpolation, there is a sad ambiguity: /$foo[bar]/ interpreted as /${foo}[bar]/ (where [bar] is the character class for the regular expression) or as /${foo[bar]}/ (where [bar] is the index for the @foo array)? Unless @foo otherwise exists, its obviously a character class. If @foo exists, Perl is well versed in [bar] and is almost always right. If he is mistaken, or if you are just paranoid, you can force the correct interpretation with curly braces, as shown above. Even if you're just smart, it's probably not a bad idea.
source share