Is there any script in Perl where $ {foo [bar]} can be syntactically correct code?

I read through O'Reilly Programming Perl, 3rd Edition, and the text says that instead of using the ambiguous search pattern /$foo[bar]/ instead, use /${foo[bar]}/ so that Perl doesn't make a mistake [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 an open-word string? I checked the error information on the Internet and can not find a mention of this error in the book. Is there some kind of script that I skip when this code can be valid?

+4
source share
3 answers

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.

+8
source
 sub bar { 1 } 

Alas, I cannot imagine this alone; it's too short for SO. So, this is one way to express a constant in Perl. For example, sub MAGIC_NUMBER { 0x7774 }

+4
source

bar may be a function:

 perl -le 'sub bar () { 1 } my @foo = qw(hello world); print m/${foo[bar]}/ ? "$_ -> TRUE" : "$_ -> FALSE" for qw(hello world)' 
0
source

Source: https://habr.com/ru/post/1400915/


All Articles