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

Hi, In perl the -> operator is used to do many things as in package->method "package"->method obj->method reference->[0] or reference->{"name"} how perl know which is of which kind. wont it get confused.Wont there be any ambiguity?

Replies are listed 'Best First'.
Re: -> operator
by moritz (Cardinal) on Nov 13, 2007 at 12:02 UTC
    There are disambiguation rules, for example:
    • If the -> is followed by braces or brackets, it's a hash or array lookup
    • Otherwise, if the LHS is a blessed reference, it's dispatched as a method call
    • If the LHS is a package name, the RHS is interpreted as a sub and the first arg is the LHS (this is quasi identical to the previous case).

    I'm sure there are more rules, but in general it does what I mean (dwim) ;-)

      If the LHS is a package name, the RHS is interpreted as a sub and the first arg is the LHS (this is quasi identical to the previous case).

      I think the word "method" is better than "sub" there, as method dispatch occurs in this case. (Use B::Concise and look for an op named fetchmethod or something similar.)

Re: -> operator
by lupey (Monk) on Nov 13, 2007 at 16:06 UTC

    The description of the arrow operator is found here

Re: -> operator
by tuxz0r (Pilgrim) on Nov 13, 2007 at 16:24 UTC
    I'm not sure what your background is, but a good reference on language grammars for interpreters and compilers is Principles of Compiler Design (the dragon book). This gives a really good description of different types of langauge parsing and how they work. I can't find a good reference on the Perl language grammar (anyone?); but it's somewhere to start.

    ---
    echo S 1 [ Y V U | perl -ane 'print reverse map { $_ = chr(ord($_)-1) } @F;'
    Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

Re: -> operator
by naikonta (Curate) on Nov 14, 2007 at 01:38 UTC
    Basically, Perl has its own way to interprete the syntax, for example to distinct the same operators or functions usage, based on some contexts. Parsing things such as $scalar->[0] or $scalar->{key}, or even $scalar->method is straightforward and will Do What I (programmer) Mean. Please see perlref for detail.
    wont it get confused.Wont there be any ambiguity?
    In case of ambiguity, Perl will try its best to Do What I (programmer) Really Mean. If it gets confused though, it may warn me, or I can make it confess to show more detail what or where it gets confused. This helps me to see that my code might not steadily represent what I mean. And if it really doesn't have any idea on some piece of code, or refuses to look further, it will die and let me informed that what and where in my code some part just doesn't make sense to it.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!