title: How to detect that the method is in the middle of the call chain in Perl?
body: <p>I have an example object with <code>calc</code> method:</p>
  
  <pre><code>package A;
  sub new {...}
  sub calc {
      my ($self, $a, $b) = @_;
      return {first =&gt; $a, second =&gt; $b, sum =&gt; $a + $b}
  }
  </code></pre>
  
  <p>And simple usage:</p>
  
  <pre><code>my $result = A-&gt;new-&gt;calc(1, 2);
  print 'Result is ', $result-&gt;{sum}; # output: Result is 3
  </code></pre>
  
  <p>Now, i want to add a chaining method <code>log</code> so that it outputs the parameters of calculation and returns result:</p>
  
  <pre><code>package A;
  ...
  sub calc {
      ...
      return $self-&gt;{result} = {...}
  }
  sub log {
      my $self = shift;
      print sprintf 'a = %d, b = %d', $self-&gt;{result}-&gt;{first}, $self-&gt;{result}-&gt;{second};
      return $self-&gt;{result};
  }
  </code></pre>
  
  <p>And use it like this cases:</p>
  
  <pre><code>my $result = A-&gt;new-&gt;calc(10, 20);
  print "Result of calc: ", $result-&gt;{sum}; # output: 30
  
  $result = A-&gt;new-&gt;calc(11, 12)-&gt;log; # output: a = 11, b = 12
  print 'Result is ', $result-&gt;{sum}; # output: Result is 23
  </code></pre>
  
  <p>I tried to use helper object with overloads, but my <code>calc</code> can return very different structures like scalar, array, arrayref, hashref... So, my helper's object code was awful and buggy.</p>
  
  <p>Now, i have two questions:</p>
  
  <ol>
  <li>Can i determine that the method is in the middle of the call chain, rather than the end? Then i could return <code>$self</code> from <code>calc</code> instead of result.</li>
  <li>Has it more elegant solution?</li>
  </ol>