This works:

use strict; use warnings; sub test_a; sub test_a { my $arg = shift; ref($arg) ? test_a$$arg[0] : $arg } sub test_b { my $arg = shift; ref($arg) ? test_a$$arg[0] : $arg } print test_b[42]; # prints '42' print test_a[42]; # prints '42'

The reason your original one fails is that while perl is parsing the body of sub test_a, it encounters test_a$$arg[0] and isn't quite sure how to parse it. You'd want to parse it like:

test_a($$arg[0])

But it actually gets parsed like this:

${ $arg }->test_a([0])

That is, it assumes you're calling the test_a method on $$arg via the indirect method syntax.

It makes this assumption because while the body of test_a is being parsed, there is no function called test_a in the symbol table. So it assumes that you cannot really mean test_a($$arg[0]).

Pre-declaring sub test_a; (as per my example) solves this. The other solution is to avoid the ambiguity in your syntax and add parentheses.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

In reply to Re: Recursive method calls and references by tobyink
in thread Recursive method calls and references by Grimy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.