Geo::GDAL  2.3

Version

These pages document the development version (2.3) of the GDAL Perl API, which is extended from the released versions APIs. Old versions: 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 2.0 2.1 2.2. The development version of these docs.

Introduction

The Geo::GDAL modules are the Perl bindings to the GDAL/OGR library. The modules allow you to use Perl to access and manipulate all geospatial data that the installed GDAL library is configured to access and manipulate.

This documentation covers the Perl bindings. For more in-depth documentation see the main documentation of GDAL. This documentation also emphasizes the recommended Perl API. Some methods and aliases to method names are left out since they may skip some built-in usability or other additions.

Usage

Makes all classes available in your Perl program. Some subroutines (Driver, Open, BuildVRT) can be imported into the main namespace with ':all'.

use Geo::GDAL qw/:all/;

Arguments

Some arguments are optional and have a default value. This is illustrated like this:

SomeMethod(arg1, arg2 = 4);

arg1 is a required argument.

arg2 may be left out and if left out, will get the value 4 (in this case).

Only the last argument or arguments can be optional.

In some cases a method can be called in a traditional way and with named arguments (i.e. with a hash):

$object->method(1, 2, 3);
$object->method(number=>1, param=>2, other=>3);
$object->method({number=>1, param=>2, other=>3});

Note especially the difference between the second and the third versions. In some cases the named arguments must be given in an anonymous hash.

In some cases a method may behave differently depending on the parameters that it gets:

$object->method($hashref); # method called with a reference to a hash
$object->method($arrayref); # method called with a reference to an array

In some cases a method may examine the context in which it is called, and behave differently:

$object->method(); # method called in void context
$return = $object->method(); # method called in scalar context
@return = $object->method(); # method called in list context

Many of the methods may throw an error, which can be caught by putting the call into eval{}; and then examining the contents of $@.

Modules, package subroutines, class methods, and object methods

Geo::GDAL is the module, which you use in your Perl program. A module is a file with .pm extension. When you use the Geo::GDAL module, it uses other modules. Geo::GDAL modules define several packages, also known as namespaces, which are usually but not always classes. Subroutines within packages may either be simply subroutines, class methods, or object methods.

Objects of a class are often created using the class method new

$object = SomeClass->new();

Object methods in packages are always invoked for objects

$object->method();

while class methods are invoked for classes

Geo::GDAL::Class->method();

and package subroutines are invoked as subroutines in namespaces

Geo::GDAL::Class::subroutine();

The distinction between class methods and package subroutines is subtle but often important. The method invocation passes the class name as the first argument while the subroutine invocation does not. Especially constructor (new) must be called as a class method.

Similar to methods, also attributes are either class attributes or object attributes. Class attributes are package variables and object attributes are variables owned by each individual object. Class attributes are used for example for enumerated values. In some cases object attributes can be accessed as hash values

$value = $object->{attribute};
$object->{attribute} = $new_value;

but this is mostly deprecated and class and object attributes should be accessed through methods.

Class attributes are also used for maintaining, e.g., is_a_part_of relationships between objects. Because Band objects are a part of Dataset objects, there is a class attribute (a hash) in Dataset, which maintains these relationships and makes sure the Dataset object that owns a Band object is not destroyed before the Band object. Also, definition objects that are linked to feature and layer objects are read-only, and this constraint is enforced using class attributes.

Exceptions

Geo::GDAL uses the Perl exception mechanism. It means that exceptions which GDAL classifies as failures trigger a Perl exception, and an exception that is classified as a warning triggers a Perl warning. Fatal errors trigger a message to standard error and an abort.

All errors are confessed (except those generated by Swig, which are croaked) in the Perl bindings, i.e., the Perl stack is included in the Perl error message $@. However, several error messages may be generated by GDAL as a result of one call and only the last error message is included in $@. The whole stack of GDAL error messages is stored in a package variable @Geo::GDAL::error. Thus, $@ and @Geo::GDAL::error give a different insight into the error. It is usually not a good idea to look directly into @Geo::GDAL::error, instead call Geo::GDAL::errstr, which returns the error stack chomped and joined into one string.

Note that it is a good idea to call Geo::GDAL::errstr(); before eval {}; to clear the error stack.

Perl exceptions can be caught by eval() and Perl warnings can be caught by signal __WARN__. Examples:

eval {
my $point = Geo::OGR::Geometry->new(WKT=>"POINTXX(1 1)");
};
say STDERR Geo::GDAL->errstr if $@;

Produces:

OGR Error: Unsupported geometry type

while

my $point = Geo::OGR::Geometry->new(WKT=>"POINTXX(1 1)");

Produces:

OGR Error: Corrupt data
at <long path>/OGR.pm line 693.
Geo::OGR::Geometry::new("Geo::OGR::Geometry", "WKT", "POINTXX(1 1)") called at foo.pl line 18

and

BEGIN {
$SIG{__WARN__} = sub { print STDERR "Warning: @_"; }
}
Geo::GDAL::GetDriver('GTiff')->Create( Name => 'my.tiff',
Width => 100,
Height => 100,
Type => 'Byte',
Options => { my_unknown_option => 'b' } );

Produces:

Warning: Driver GTiff does not support my_unknown_option creation option at site/lib/Geo/GDAL.pm line 771.

Environment variable CPL_DEBUG

Setting $ENV{CPL_DEBUG} to 'ON' makes GDAL verbose about many non-fatal things. It may be useful in trying to figure out what is going on internally. GDAL uses its normal error mechanism to report the debug messages. This means that the messages will end up in @Geo::GDAL::error and can be accessed with Geo::GDAL::errstr. That can be changed by calling Geo::GDAL::DontUseExceptions, after which all error and debug messages are sent to standard error (STDERR). For example

$ENV{CPL_DEBUG} = 'ON';
my $mp = Geo::OGR::Geometry->new(GeometryType => 'MultiPoint', Points => [[1,1]]);
$mp->AddGeometry(Geo::OGR::Geometry->new(GeometryType => 'Point'));
say $mp->As(Format => 'ISO WKT');

Prints

OGR: OGRMultiPoint::exportToWkt() - skipping POINT EMPTY.

to STDERR, and

MULTIPOINT ((1 1))

to STDOUT.

Named parameters

Quite many methods and subroutines in Geo::GDAL accept named parameters. In all cases the named parameters are handled with the same filter, which accepts either a list of parameters (the order is the order in which the named parameters are described in this documentation), single hash reference, or a list of key value pairs. The keys are given in the documentation but the filter ignores case and underscores. Thus, although the name of the parameter is ProgressData, the method will happily recognize also progress_data.

Progress callback

Some methods accept a callback function for reporting the progress. The progress subroutine is called with three arguments: a number, a string, and user defined data. The user defined data is an argument to the method.

sub progress {
my($progress, $message, $data) = @_;
my $terminate = 0;
...
return $terminate ? 0 : 1;
}

Redirecting stdout to a writer object

The Perl bindings takes advantage of the virtual file system of GDAL and offers a way to redirect the output from a format driver to a Perl object. The object needs to implement write and close methods. write is called for each output from the driver with the output byte string as an argument. close is called when the dataset being used in the creation is destroyed. Note that the destruction of the dataset may depend on destruction of all objects that depend on it. For a simple example see page Streaming a dataset.

Due to the limitation of the redirection mechanism only one redirection may be active at any time.

Note that the return value of the write method does not have any effect. Internally the return value is set to the length of the byte string.

Reference counting

In GDAL many objects may depend on other objects to exist, for example a geometry, which is an attribute of a feature depends on the feature to exist when the geometry is accessed. If a feature is destroyed, then using a geometry object, which points for its data into the feature, will lead to memory error.

GDAL maintains its own reference counting but this is largely lost in the bindings.

The Perl bindings attempt to maintain these dependencies by keeping the parent objects alive under the hood, independent of their existence in the user space. Thus it is perfectly legal to do something like

my $layer = Geo::OGR::Driver('Memory')->
Create()->
CreateLayer(Name => 'layer',
Fields => [{Name => 'test', Type => 'Integer'},
{Name => 'geom', Type => 'Point'}]);

or

my $geometry;
{
my $feature = $layer->InsertFeature({test => 13, geom => {WKT => 'POINT (10 20)'}});
$geometry = $feature->Geometry('geom');
}
say $geometry->AsText;

There is at least one caveat. Swig sets the bindings up in such a way that the objects are tied hashes. For example a feature can used as a hash.

my $feature = $lauer->InsertFeature({test => 13, geom => {WKT => 'POINT (10 20)'}});
my $test = $feature->{test};

Due to the mechanism of tied hashes in Perl it is not possible to maintain the parent referencing when using this syntax. Thus do not use this for subobjects. (In fact it will create an error.)

my $feature = $lauer->InsertFeature({test => 13, geom => {WKT => 'POINT (10 20)'}});
my $geom = $feature->{geom}; # will lead to memory error!

Processing options

Some methods are thin wrappers for GDAL command line tools.

The options for these methods should be given in an anonymous hash where the key is the option name (-ot, -mask, etc) and the value is the option value. If the option expects a list of values, the list should be given as a reference to an array.

In addition to the above, the API supports giving the options in an anonymous array; keys without hyphen (not if the options are in an array); and lists of values given as a string, separated with whitespace (only for lists of numeric values).

Note

This documentation is generated from files within the GDAL distribution (directory swig/perl) with Doxygen using a Perl module Doxygen::Filter::Perl. A tailor made preprocessor in the GDAL distribution is used to process and put all Perl code and documentation into a single file (all.pm) for Doxygen-Filter-Perl and Doxygen.

Many methods are just interfaces to non-Perl code in the bindings or GDAL and thus their code show as blank on these pages. The bindings are created with Swig, which adds some methods by default.

Code examples in method pages contain dots ('.') to enforce indentation. This is due to a doxygen bug.