txt: ## sub.md
  sub
  
  Combined from primary sources listed below.
  
  # [In Functions](#___top "go to top of document")[§](#(Functions)_sub_sub "direct link")
  
  See primary documentation
  [in context](/language/functions#Subroutines)
  for **Subroutines**.
  
  The basic way to create a subroutine is to use the `sub` declarator followed by an optional [identifier](/language/syntax#Identifiers):
  
  ```raku
  sub my-func { say "Look ma, no args!" }
  my-func;
  ```
  
  The sub declarator returns a value of type [`Sub`](/type/Sub) that can be stored in any container:
  
  ```raku
  my &c = sub { say "Look ma, no name!" }
  c;     # OUTPUT: «Look ma, no name!␤»
  
  my Any:D $f = sub { say 'Still nameless...' }
  $f();  # OUTPUT: «Still nameless...␤»
  
  my Code \a = sub { say ‚raw containers don't implement postcircumfix:<( )>‘ };
  a.();  # OUTPUT: «raw containers don't implement postcircumfix:<( )>␤»
  ```
  
  The declarator `sub` will declare a new name in the current scope at compile time. As such, any indirection has to be resolved at compile time:
  
  ```raku
  constant aname = 'foo';
  sub ::(aname) { say 'oi‽' };
  foo;
  ```
  
  This will become more useful once macros are added to Raku.
  
  To have the subroutine take arguments, a [`Signature`](/type/Signature) goes between the subroutine's name and its body, in parentheses:
  
  ```raku
  sub exclaim ($phrase) {
      say $phrase ~ "!!!!"
  }
  exclaim "Howdy, World";
  
  ```
  
  By default, subroutines are [lexically scoped](/syntax/my). That is, `sub foo {...}` is the same as `my sub foo {...}` and is only defined within the current scope.
  
  ```raku
  sub escape($str) {
      # Puts a slash before non-alphanumeric characters
      S:g[<-alpha -digit>] = "\\$/" given $str
  }
  
  say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
  
  {
      sub escape($str) {
          # Writes each non-alphanumeric character in its hexadecimal escape
          S:g[<-alpha -digit>] = "\\x[{ $/.ord.base(16) }]" given $str
      }
  
      say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤»
  }
  
  # Back to original escape function
  say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
  
  ```
  
  Subroutines don't have to be named. If unnamed, they're called *anonymous* subroutines.
  
  ```raku
  say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # OUTPUT: «25␤»
  ```
  
  But in this case, it's often desirable to use the more succinct [`Block`](/type/Block) syntax. Subroutines and blocks can be called in place, as in the example above.
  
  ```raku
  say -> $a, $b { $a ** 2 + $b ** 2 }(3, 4)    # OUTPUT: «25␤»
  ```
  
  Or even
  
  ```raku
  say { $^a ** 2 + $^b ** 2 }(3, 4)            # OUTPUT: «25␤»
  ```
  