Friday, December 4, 2015

Perl6 and subroutines

The old way almost works.  You can't use shift, but if you mind the Perl6 sigil you're good:

   sub hello 
   {
      my $who = @_[0];
      print "hello, $who\n";
   }

> hello('Dave')
hello, Dave


But the new way is  S O   M U C H   B E T T E R:

   sub hello($who)
   {
      say "hello, $who";
   }

> hello('Dave')
hello, Dave


Oh it's about time!  And if you're working with lots of programmers and are paranoid about type checking:

   sub hello(Str $who)
   {
      say "I'm sorry $who, I'm afraid I can't do that";
   }

> hello('Dave')
I'm sorry Dave, I'm afraid I can't do that.


> hello(3)
CHECK FAILED:
Calling 'hello' will never work with argument types (int) (line 1)
    Expected: :(Str $name)





No comments:

Post a Comment