This is the first "serious" thing I'm doing in Perl, so please pardon me if the question is somewhat silly.
I wanted to play around with the A* pathfinding algorithm. I found the AI::Pathfinding::AStar CPAN Module and am basically trying to get the given example to work.
First of all I separated the example into two files, because I couldn't figure out how to make the use My::Map::Package;
work with everything in a single file. I came up with the following two files:
MyAstar.pm:
package MyAstar;
use warnings;
use strict;
use base "AI::Pathfinding::AStar";
my %NODES = get_all_nodes();
sub get_all_nodes {...}
sub getSurrounding {...}
main.pl:
#!/usr/bin/env perl
package main;
use lib '/home/foo/astar/';
use warnings;
use strict;
use MyAstar;
my $map = MyAstar->new or die "No map for you!";
my $path = $map->findPath(1, 5);
print join(', ', @$path), "\n";
When I execute main.pl I get the following error:
Can't locate object method "new" via package "MyAstar" at main.pl line 9.
I'm not sure what the problem is here. I would have expected, there to be a subroutine by the name new
in the AI::Pathfinding::AStar
package, but couldn't find it. Is the CPAN Module broken or am I doing something wrong?
You try to call a function (MyAstar->new
, which conventionally is used as a constructor), but you don't define it. There is no default constructor in Perl (like in e.g., Java).
Add something like this to your MyAstar.pm:
sub new {
my $class = shift;
my $self = bless{}, $class;
# initialize $self here as needed, maybe using any passed arguments in @_
return $self;
}