develooper Front page | perl.perl6.users | Postings from June 2022

trouble returning a value from sub

Thread Next
From:
Rick Bychowski
Date:
June 16, 2022 17:10
Subject:
trouble returning a value from sub
Message ID:
339f85f7-e59a-7aad-c2bb-f96993321867@hiranyaloka.com
Hi Everyone,

I've been lurking quite a while, this will be my first post to perl6 
users. I've written a lot of short scripts in perl5 for system admin 
type stuff at home and work. Lately I'm playing with Raku, which is a 
lot of fun. Error reporting is excellent, as is the online documentation.

To the point. I recently started the perl weekly challenge. Lots of 
math/primes stuff. I wrote an algorithm to list all the prime factors of 
an integer, using a recursive subroutine. I'm able to print the result 
from the subroutine, but it always returns Nil. What am I missing?

#!/usr/bin/env raku

sub MAIN($n = 20) {
    .say for factors($n); # Nil
}

sub factors($n, @factors?) {
     my @f = @factors.elems ?? @factors !! ();
     my $q;
     for 2 ..^ $n -> $i {
         if $n %% $i {
             $q = Int($n / $i);
             @f.push($i);
             if $q.is-prime {
                 @f.push($q);
                 say @f;    # [2 2 5]
                 return @f;
             } else {
                 factors($q, @f);
             }
             last;
         }
     }
}

Returns
[2 2 5]
Nil

-- 
Rick Bychowski

The information in this email is confidential and may be legally 
privileged. It is intended solely for the addressee(s). Access to this 
e-mail by anyone else is unauthorized.

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