Commented braces
am 12.09.2007 11:03:01 von Michele DondiThis is something obvious, but it may not be entirely obvious to all.
So I'm copying it here for the benefit of potential readers.
Originally from:
http://perlmonks.org/?node_id=638287
Original question (sanPerl)
------------------------------------
Dear Monks,
I am trying to execute the code given below.
use strict;
my $abcd = "Hello how r you?";
my $hello="Hello";
$abcd =~ s{\w}
{
#{
#}{
if ($hello)
{"1"}
else
{"0"}
}exgs;
print $abcd;
It is giving me error
Substitution replacement not terminated at test.pl line 5.
When I removed line 6 & 7 the code looked as below
use strict;
my $abcd = "Hello how r you?";
my $hello="Hello";
$abcd =~ s{\w}
{
if ($hello)
{"1"}
else
{"0"}
}exgs;
print $abcd;
It works proper and gives me output 11111 111 1 111? My question is,
why the commented braces are playing role in this error ? Have I done
something wrong here?
Reply (moritz)
------------------------------------
The problem is that the code is potentially ambigous.
There are two ways to parse it:
s{...}{
# much stuff here
}x
The other, but less obvious, ist this:
s{...}{
# some characters
{}{
# more characters...
}
# no terminator
When perl tries to parses the regex it doesn't know if there is going
to come an /x modifier, so the braces have to be balanced - even in
comments.
That's one of the reasons Perl 6 puts the modifiers at the start of
the regexes.
Reply (ikegami)
------------------------------------
If Perl were to guess that "#" indicates a comment, it'll introduce a
paradox. Consider
s{foo}{
bar
#}xe
}
If Perl stops at the second "}", then the replacement expression is
not code and "#" are not comments and Perl should have stopped at the
first "}".
If Perl stops at the first "}", then the replacement expression is
code ("e") and "#" are comments ("x") and Perl should have stopped at
the second "}".
Perl needs to find the end of the operator to find the "e" and "x"
flags. To find the end of the operator, Perl initially treats the
expression as a replacement string. When the "e" flag is found is the
replacement string is reparsed as code. Only then does "x" have any
meaning.
Perl 6 fixes this by placing the flags before the replacement
expression.
------------------------------------
Other replies at the link above.
Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^