Learning Perl
Day 1
Learn the basics.
Helpful resources:
Day 2
Practice on real world problems (Project Euler).
My current goal is to learn the language and not to find the optimal solution.
3. Prime factorization
#!/usr/bin/perl
use strict;
use warnings;
my @primes;
die "(script waits for exactly one argument)\n" unless(scalar @ARGV == 1);
CANDIDATE: for my $candidate ( 2 .. 10000 ) {
for my $divisor ( 2 .. sqrt $candidate ) {
next CANDIDATE if $candidate % $divisor == 0;
}
push @primes, $candidate;
}
my $num = $ARGV[0];
my @primeFactors = ();
my $q = $num;
while((scalar grep{$_ == $q} @primes) == 0) {
ITERATION: foreach(@primes) {
if($q % $_ == 0) {
push @primeFactors, $_;
$q = $q / $_;
last ITERATION;
}
}
}
print "$num: @primeFactors $q\n";
48. Self powers
#!/usr/bin/perl
use strict;
use warnings;
use Math::BigInt;
my $result = Math::BigInt->new(0);
$result->badd(Math::BigInt->new($_)->bpow($_)) for (1 .. 1000);
print(substr("$result", -10),"\n");