This post originated from an RSS feed registered with Perl Buzz
by Andy Lester.
Original Post: Diving into Perl 6
Feed Title: Perlbuzz
Feed URL: http://perlbuzz.com/atom.xml
Feed Description: What's happening in the world of Perl programming, including Perl 5, Perl 6, the CPAN and Parrot?
I wrote my first real Perl 6 from scratch today. It's a prime number tester, where we test both via checking factors iteratively, and also using the magic prime number tester regular expression. I was inspired by a blog post about how PHP can't always handle regexes with lots of backtracking, and I thought it would make a good stress for Perl 6.
My program as it stands now looks like this:
#!/usr/local/bin/perl6
use v6;
# Perl 5 @ARGV is now @*ARGS
my Int @candidates;
if ( @*ARGS ) {
for @*ARGS -> $n {
push @candidates, $n.Int;
}
}
else {
@candidates = 2 .. 100;
}
for @candidates -> Int $x {
my $via_factors = is_prime_via_factors($x);
my $via_regex = is_prime_via_regex($x);
if $via_factors && $via_regex {
say "$x is prime";
}
elsif $via_factors xor $via_regex {
say "Difference in opinion on $x :",
"factors says $via_factors, regex says $via_regex";
}
}
sub is_prime_via_factors( Int $n ) returns Bool {
my $top = sqrt $n;
for 2..$top -> $i {
return False if $n %% $i;
# %% is the divisible-by operator
}
# Could also use: $n %% none(2 .. $top)
return True;
}
sub is_prime_via_regex( Int $n ) returns Bool {
my $str = 'x' x $n;
# First capture is $0, not $1 or \1 as in Perl 5
return False if $str ~~ regex { ^ x $ | ^ (xx+?) $0+ $ };
return True;
}
I'm sure there are ways that are more Perl 6ish to do what I've done above, but I was glad to learn along the way. Big thanks to the #perl6 IRC channel for help. Some important lessons:
Command-line args are in @*ARGS, not @ARGV.
The old chestnut ($x mod $y == 0) is now ($x %% $y) with the %% divisible-by operator.
The first capture group in a regex is $0, not $1 or \1 as in Perl 5.
My goal is to have all of perl101.org include examples in both Perl 5 and Perl 6, both for people new to Perl and for those moving to Perl 6. If you'd like to help in this effort, let me know or work on the perl101 github project.