> On 21/01/2020 04:09, ToddAndMargo via perl6-users wrote:
>> On 2020-01-20 19:55, ToddAndMargo via perl6-users wrote:
>>> Hi All,
>>>
>>> What is the proper way to state that I am returning a
>>> hash from a sub?   `sub x() returns % {}`
>>>
>>> And an array?  `sub x() returns @ {}`
>>>
>>> Many thanks,
>>> -T
>>
>>
>> I think this is it:
>>
>> > sub x() returns Associative { my %h= A=>"a"; return %h}
>> &x
>> > x
>> {A => a}
>>
>>
>> > sub y() returns Array { my @a=(1,2,3,2,1) ; return @a}
>> &y
>> > y
>> [1 2 3 2 1]
>>
>>
>> Am I too high up the food chain with Associative and Array?
>>
>> -T

On 2020-01-21 13:37, Richard Hainsworth wrote:
sub x( --> Hash) { my %h = A => 'a' }

1) '-->' in the signature is the best way to provide information to the compiler about what the subroutine should return

2) 'returns' in the declaration (not the part in the block) used to be used, but for some arcane reason that I never really understood, it is deprecated.

3) 'Hash' or 'Associative'. These all refer to roles that a hash will 'do'.

4) A block (that is the { ... } bit) will always 'return' the last expression evaluated.

Seems to me I have see the last expression returned even without
the {...}.  Maybe I am misremembering.


So there is no need for the 'return %h' in your code. 'return ...' is only needed if you  have some logic where the block can exit in several places, not just the last expression.

5) To specify an 'array', you can use 'sub x( --> Array) { my @a = 1..* }'

6) HOWEVER, you really do need to read the documentation about Sequences, lists and arrays.

Richard


I have always used "return" to make it more readable.  And
sometimes I will return before end of the sub.   I can
type, so extra words don't bother me.

Nice exposition!  Thank you!

Reply via email to