develooper Front page | perl.perl5.porters | Postings from July 2016

Forward declaration and recursion

Thread Next
From:
Ed Avis
Date:
July 4, 2016 13:53
Subject:
Forward declaration and recursion
Message ID:
loom.20160704T151803-796@post.gmane.org
This works:

   sub foo {
       my $x = shift;
       return $x * 2;
   }
   my $r = foo 5;
   print $r;

You can call foo without the explicit ().  But one place where you can't omit
the brackets is inside the body of foo itself.

   sub foo {
       my $x = shift;
       if ($x == 0) { return 0 }
       --$x;
       return 2 + foo $x;        # fails - taken as object method
   }
   my $r = foo 5;
   print $r;

You can resolve this by adding a forward declaration:

   sub foo;
   sub foo {
       ...

But this seems un-Perlish.  Could lookup rules be tweaked so that a subroutine
can make recursive calls without needing explicit parentheses or a forward
declaration?

I think it is fair enough that if a subroutine hasn't been mentioned yet
then you have to use the explicit () to call it, but this is a bit 
surprising inside the body of the subroutine itself.

-- 
Ed Avis <eda@waniasset.com>


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About