#!/usr/bin/pugs use v6; ############################################################ ###Perl5ish subroutine declarations#### tmp(3,'asd',4); moditest(100); sub tmp { say ~@_; } ## @_ is rw to do in pugs sub moditest (*@_ is rw) { say "val is @_[0]"; #@_[0] = 99 ; #say "modified val is @_[0]"; } ############################################################ ### Multi Sub### foo ('string_passed'); foo (4); foo($*ERR); # type based dispatching multi sub foo (Int $bar) { say "Int " ~ $bar } multi sub foo (Str $bar) { say "Str " ~ $bar } multi sub foo (IO $fh) {say "IO" } ############################################################ ###Pointy Sub### my ($sub, $got); $got = ''; $sub = -> $x { $got = "x $x" }; say $sub.(123); $sub = -> ($x) { $got = "x $x" }.(456).say; my $str = ''; ### Output of the below ##start outer ## before ## pointy still sees outer's &outer ##calling outerinner ret ##str is inner ## End Output say " calling outer" ~ outer(); say "str is " ~ $str; sub outer { say "start outer"; my $s = -> $x { say " pointy still sees outer\'s $?SUBNAME"; $str ~= 'inner'; return 'inner ret'; }; say " before "; $s.(); $str ~= 'outer'; say " In Outer $?SUBNAME"; return 'outer ret'; } ############################################################ ###Optional Parameters ### ## Optional positional parameters are specified after all the ## required parameters and each is marked with a ? before the parameter my_substr('Kiran'); my_substr("foobar",len=>3); sub my_substr ($str, ?$from = 100, ?$len = Inf) { say "str is $str from is $from len is $len"; } say "calling " ~ xml_tag('sometag'); sub xml_tag ($tag, ?$endtag = matching_tag($tag) ) { say "tag is $tag endtag is $endtag"; } sub matching_tag ($tmp) { return "GOtta $tmp"; } ############################################################ ###Named Parameters ### #Named parameters follow any required or optional parameters in the signature. # They are marked by a + before the parameter. my ($text,$case,$justify) = formalize('title', case=>'upper'); say "text is $text case is $case justify is $justify "; ($text,$case,$justify) = formalize('head', justify=>'right',case=>'lower'); say "text is $text case is $case justify is $justify "; ($text,$case,$justify) = formalize('head', :justify,:case);# another way say "text is $text case is $case justify is $justify "; sub formalize($text, +$case, +$justify) returns List { return($text,$case,$justify); } ############################################################ ###Slurrrp ### #Slurpy parameters follow any required or optional parameters. #They are marked by a * before the parameter: my @arr = 1..3; # array stores three scalars #bar(@arr); # error: only one arg bar(@arr); # ok sub bar(*$x, *$y, *$z) { say "x $x"; say "y $y "; say "z $z"; }