hurricup has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Monks!

New parsing question here. This time about % char. Which can be a hash sigil or mod operator

Example:

use strict; package Foo; sub new{return bless {}, 'Foo';} sub mysub{ say "invoked foo->mysub"; } package main; sub mysub{ say "invoked mysub";} my $foo = Foo->new(); $foo->mysub % 2; $foo->mysub %2; mysub % 2; mysub %2;
No prototype in main sub and no prototype in Foo sub (object invocation are ignoring it anyway). Deparse gives me:
package Foo; sub new { use strict; return bless({}, 'Foo'); } sub mysub { use strict; print "invoked foo->mysub\n"; } package main; sub mysub { use strict; print "invoked mysub\n"; } use strict; my $foo = 'Foo'->new; $foo->mysub % 2; $foo->mysub % 2; mysub %2; mysub %2;
Object invocation treats % as mod operator. And sub invocation treats as hash sigil. Why so?

Replies are listed 'Best First'.
Re: Ambiguous % parsing
by choroba (Cardinal) on Jul 21, 2015 at 10:15 UTC
    Arguments to methods must be specified in parentheses when using the arrow notation. There's no way how to parse
    $foo->mysub %2
    as a method call followed by a hash.

    Interestingly, such a parse is possible in the indirect object notation:

    method $obj %2

    nevertheless, Perl parses that as modulo, too:

    perl -MO=Deparse,-p -e 'method $o 2; method $o %2' $o->method(2); ($o->method % 2); -e syntax OK
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Ambiguous % parsing
by dave_the_m (Monsignor) on Jul 21, 2015 at 10:15 UTC
    Because method calls don't consume args without parentheses; this is a syntax error:
    $obj->foo 1;
    Sub calls only work without parentheses if the sub has been pre-declared (so the parser knows that 'foo' is a sub name):
    foo 1; # syntax error sub foo {} foo 2; # ok

    Dave.

Re: Ambiguous % parsing
by Anonymous Monk on Jul 21, 2015 at 10:21 UTC
    Barewords/prototypes. Known/seen Subs take args without parens, methods need parens for args
Re: Ambiguous % parsing
by hurricup (Pilgrim) on Jul 21, 2015 at 10:31 UTC

    Thanks!