10

This works,

print map { $_." x" => $_ } 1..5;
print map { ("$_ x" => $_) } 1..5;
print map { ("$_ x") => $_ } 1..5;

but this throws syntax error,

print map { "$_ x" => $_ } 1..5;

Is this documented bug, undocumented bug, or I can't see why this should not compile?

Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST

5
  • I don't think this is a bug, just an example of Perl "guessing wrong" between map BLOCK LIST and map EXPR, LIST, which is documented toward the end of perldoc -f map. Hopefully somebody can explain exactly why Perl guesses the way it does for your examples in an answer. Jul 1, 2015 at 15:26
  • @ThisSuitIsBlackNot yes, it looks that way eval.in/390502 but usually map EXPR, LIST requires + in front of EXPR. Otherwise it is a BLOCK.
    – mpapec
    Jul 1, 2015 at 15:33
  • 2
    @Сухой27 no, map EXPR does not usually require a +. Perl usually guesses well. Here, it looks like you are creating an anonymous hash, not a block.
    – ysth
    Jul 1, 2015 at 15:47
  • @ysth in first three examples which are basically same thing, it guesses BLOCK as expected.
    – mpapec
    Jul 1, 2015 at 15:50
  • The "why" probably can't be answered without looking at the code for Perl's parser. (Anybody?) Also, you can see the same parsing behavior without map. perl -we'{"x"."y"=>1}', perl -we'{("x"=>1)}', and perl -we'{("x")=>1}' all give Useless use of a constant in void context warnings (parsed as a block); perl -we'{"x"=>1}' gives Useless use of anonymous hash in void context (parsed as an expression). Jul 1, 2015 at 16:18

2 Answers 2

6

From perlref

Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.

To make your intentions clearer and to help the parser,

  • Say +{...} to unambiguously specify a hash reference

    @list_of_hashrefs = map +{ "$_ x" => $_ }, 1..5;
    
  • Say {; ...} to unambiguously specify a code block

    %mappings = map {; "$_ x" => $_ } 1..5;
    
1
  • Tnx, but this doesn't explain why similar constructs are interpreted as BLOCK while one particular is viewed as EXPR.
    – mpapec
    Jul 2, 2015 at 5:22
3

Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST?

The relevant section of code is in toke.c, Perl's lexer (the below is from Perl 5.22.0):

/* This hack serves to disambiguate a pair of curlies
 * as being a block or an anon hash.  Normally, expectation
 * determines that, but in cases where we're not in a
 * position to expect anything in particular (like inside
 * eval"") we have to resolve the ambiguity.  This code
 * covers the case where the first term in the curlies is a
 * quoted string.  Most other cases need to be explicitly
 * disambiguated by prepending a "+" before the opening
 * curly in order to force resolution as an anon hash.
 *
 * XXX should probably propagate the outer expectation
 * into eval"" to rely less on this hack, but that could
 * potentially break current behavior of eval"".
 * GSAR 97-07-21
 */
t = s;
if (*s == '\'' || *s == '"' || *s == '`') {
    /* common case: get past first string, handling escapes */
    for (t++; t < PL_bufend && *t != *s;)
        if (*t++ == '\\')
            t++;
    t++;
}
else if (*s == 'q') {
    if (++t < PL_bufend
        && (!isWORDCHAR(*t)
            || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
                && !isWORDCHAR(*t))))
    {   
        /* skip q//-like construct */
        const char *tmps;
        char open, close, term;
        I32 brackets = 1;

        while (t < PL_bufend && isSPACE(*t))
            t++;
        /* check for q => */
        if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
            OPERATOR(HASHBRACK);
        }
        term = *t;
        open = term;
        if (term && (tmps = strchr("([{< )]}> )]}>",term)))
            term = tmps[5];
        close = term;
        if (open == close)
            for (t++; t < PL_bufend; t++) {
                if (*t == '\\' && t+1 < PL_bufend && open != '\\')
                    t++;
                else if (*t == open)
                    break;
            }
        else {
            for (t++; t < PL_bufend; t++) {
                if (*t == '\\' && t+1 < PL_bufend)
                    t++;
                else if (*t == close && --brackets <= 0)
                    break;
                else if (*t == open)
                    brackets++;
            }
        }
        t++;
    }
    else
        /* skip plain q word */
        while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
             t += UTF8SKIP(t);
}
else if (isWORDCHAR_lazy_if(t,UTF)) {
    t += UTF8SKIP(t);
    while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
         t += UTF8SKIP(t);
}
while (t < PL_bufend && isSPACE(*t))
    t++;
/* if comma follows first term, call it an anon hash */
/* XXX it could be a comma expression with loop modifiers */
if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
                   || (*t == '=' && t[1] == '>')))
    OPERATOR(HASHBRACK);
if (PL_expect == XREF)
{
  block_expectation:
    /* If there is an opening brace or 'sub:', treat it
       as a term to make ${{...}}{k} and &{sub:attr...}
       dwim.  Otherwise, treat it as a statement, so
       map {no strict; ...} works.
     */
    s = skipspace(s);
    if (*s == '{') {
        PL_expect = XTERM;
        break;
    }
    if (strnEQ(s, "sub", 3)) {
        d = s + 3;
        d = skipspace(d);
        if (*d == ':') {
            PL_expect = XTERM;
            break;
        }
    }
    PL_expect = XSTATE;
}
else {
    PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
    PL_expect = XSTATE;
}

Explanation

If the first term after the opening curly is a string (delimited by ', ", or `) or a bareword beginning with a capital letter, and the following term is , or =>, the curly is treated as the beginning of an anonymous hash (that's what OPERATOR(HASHBRACK); means).

The other cases are a little harder for me to understand. I ran the following program through gdb:

{ (x => 1) }

and ended up in the final else block:

else {
    PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
    PL_expect = XSTATE;
}

Suffice it to say, the execution path is clearly different; it ends up being parsed as a block.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.