SPVM Example - sum even numbers with precompiling.

I released SPVM 0.0441 today.

Sum even numbers with precompiling

SPVM is Static Perl Virtual Machine. I write an example to sum even numbers with precompiling.

Using precompiling, the source code is output to C source code and it is compiled to machine code. This performance is same as C language in add operation! You are surprised.

use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/lib";

use SPVM 'Even';

my $nums = [1, 3, 6, 8, 14];

my $even_sum = Even->even_sum($nums);

print "$even_sum\n";

# lib/Even.spvm
package Even {
  precompile sub even_sum : int ($nums : int[]) {
    
    my $total = 0;
    for (my $i = 0; $i < @$nums; $i++) {
      my $num = $nums->[$i];
      if ($num % 2 == 0) {
        $total += $num;
      }
    }
    
    return $total;
  }
}

If you make a subroutine precompiling, you only add a precompile option before sub.

And you must create "spvm_build" directory in the same as script directory.

spvm_build

In this directory, C source and shared library file is output.

one of SPVM purposes is creating machine code using Perl syntax.

SPVM syntax is the 95% same as Perl subset except for having static types.

Leave a comment

About Yuki Kimoto

user-pic I'm Perl Programmer. I LOVE Perl. I want to contribute Perl community and Perl users.