File: NS.pm

package info (click to toggle)
librdf-ns-perl 20120521-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 400 kB
  • sloc: perl: 161; makefile: 14
file content (293 lines) | stat: -rw-r--r-- 8,886 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use strict;
use warnings;
package RDF::NS;
{
  $RDF::NS::VERSION = '20120521';
}
#ABSTRACT: Just use popular RDF namespace prefixes from prefix.cc

use Scalar::Util qw(blessed);
use File::ShareDir;

our $AUTOLOAD;
our $FORMATS = qr/ttl|n(otation)?3|sparql|xmlns|txt|beacon/;

sub new {
    my $class   = shift;
    my $version = shift || 'undef';
	$version = $RDF::NS::VERSION if $version eq 'any';
    LOAD( $class, File::ShareDir::dist_file('RDF-NS', "$version.txt" ), @_ );
}

sub LOAD {
    my ($class, $file, %options) = @_;
    $class = ref($class) || $class;

    my $warn = $options{'warn'};

    my $ns = { };
    open (my $fh, '<', $file) or die "failed to open $file";
    foreach (<$fh>) {
        chomp;
        next if /^#/;
        my ($prefix, $namespace) = split "\t", $_;
        if ( $prefix =~ /^(isa|can|new|uri)$/ ) {
            warn "Cannot support prefix '$prefix'" if $warn;
            next;
        } elsif ( $prefix =~ /^[a-z][a-z0-9]*$/ ) {
            if ( $namespace =~ /^[a-z][a-z0-9]*:[^"<>]*$/ ) {
                $ns->{$prefix} = $namespace;
            } elsif( $warn ) {
                warn "Skipping invalid $prefix namespace $namespace";
            }
        } elsif ( $warn ) {
            warn "Skipping unusual prefix '$prefix'";
        }
    }

    bless $ns, $class;
}

sub FORMAT {
    my $self = shift;
	my $format = shift || "";
    $format = 'TTL' if $format =~ /^n(otation)?3$/i;
    if (lc($format) =~ $FORMATS) {
	    $format = uc($format);
	    $self->$format( @_ );
	}
}

sub TTL {
    my $self = shift;
    $self->MAP( sub { "\@prefix $_: <".$self->{$_}."> ." } , @_ );
}

sub SPARQL {
    my $self = shift;
    $self->MAP( sub { "PREFIX $_: <".$self->{$_}.">" } , @_ );
}

sub XMLNS {
    my $self = shift;
    $self->MAP( sub { "xmlns:$_=\"".$self->{$_}."\"" } , @_ );
}

sub TXT {
    my $self = shift;
    $self->MAP( sub { "$_\t".$self->{$_} } , @_ );
}

sub BEACON {
    my $self = shift;
    $self->MAP( sub { "#PREFIX: ".$self->{$_} } , @_ );
}

sub SELECT {
    my $self = shift;
    $self->MAP( sub { $_ => $self->{$_} } , @_ );
}

# functional programming rulez!
sub MAP {
    my $self = shift;
    my $code = shift;
    my @ns = @_ ? (grep { $self->{$_} } map { split /[|, ]+/ } @_) 
        : keys %$self;
    if (wantarray) {
        return map { $code->() } sort @ns;
    } else {
        local $_ = $ns[0];
        return $code->();
    }
}

sub GET {
    $_[1];
}

sub BLANK {
}

sub URI {
    my $self = shift;
	return $1 if $_[0] =~ /^<([a-zA-Z][a-zA-Z+.-]*:.+)>$/;
	return $self->BLANK($_[0]) if $_[0] =~ /^_(:.*)?$/;
    return unless shift =~ /^([a-z][a-z0-9]*)?([:_]([^:]+))?$/;
    my $ns = $self->{ defined $1 ? $1 : '' };
    return unless defined $ns;
    return $self->GET($ns) unless $3;
    return $self->GET($ns.$3);
}

sub AUTOLOAD {
    my $self = shift;
    return unless $AUTOLOAD =~ /^.*::([a-z][a-z0-9]*)?(_([^:]+)?)?$/;
	return $self->BLANK( defined $3 ? "_:$3" : '_' ) unless $1;
    my $ns = $self->{$1} or return;
    my $local = defined $3 ? $3 : shift;
    return $self->GET($ns) unless defined $local;
    return $self->GET($ns.$local);
}

1;


__END__
=pod

=head1 NAME

RDF::NS - Just use popular RDF namespace prefixes from prefix.cc

=head1 VERSION

version 20120521

=head1 SYNOPSIS

  use RDF::NS '20120521';              # check at compile time
  my $ns = RDF::NS->new('20120521');   # check at runtime

  $ns->foaf;               # http://xmlns.com/foaf/0.1/
  $ns->foaf_Person;        # http://xmlns.com/foaf/0.1/Person
  $ns->foaf('Person');     # http://xmlns.com/foaf/0.1/Person
  $ns->URI('foaf:Person'); # http://xmlns.com/foaf/0.1/Person

  use RDF::NS;             # get rid if typing '$' by defining a constant
  use constant NS => RDF::NS->new('20111208');
  NS->foaf_Person;         # http://xmlns.com/foaf/0.1/Person

  $ns->SPAQRL('foaf');     # PREFIX foaf: <http://xmlns.com/foaf/0.1/>
  $ns->TTL('foaf');        # @prefix foaf: <http://xmlns.com/foaf/0.1/> .
  $ns->XMLNS('foaf');      # xmlns:foaf="http://xmlns.com/foaf/0.1/"

  # get RDF::Trine::Node::Resource instead of strings
  use RDF::NS::Trine;      # requires RDF::Trine
  $ns = RDF::NS::Trine->new('20120521');
  $ns->foaf_Person;        # iri('http://xmlns.com/foaf/0.1/Person')

  # load your own mapping
  $ns = RDF::NS::LOAD("mapping.txt");

  # select particular mappings
  %map = $ns->SELECT('rdf,dc,foaf');
  $uri = $ns->SELECT('foo|bar|doz'); # returns first existing namespace

  # instances of RDF::NS are just blessed hash references
  $ns->{'foaf'};           # http://xmlns.com/foaf/0.1/
  bless { foaf => 'http://xmlns.com/foaf/0.1/' }, 'RDF::NS';
  print (scalar %$ns) . "prefixes\n";

=head1 DESCRIPTION

Hardcoding URI namespaces and prefixes for RDF applications is neither fun nor
maintainable.  In the end we all use more or less the same prefix definitions,
as collected at L<http://prefix.cc>. This module includes all these prefixes as
defined at specific snapshots in time. These snapshots correspond to version
numbers of this module. By selecting particular versions, you make sure that
changes at prefix.cc won't affect your scripts.

The command line client L<rdfns> is installed automatically with this module:

  $ rdfns -ttl rdf,foaf
  @prefix foaf: <http://xmlns.com/foaf/0.1/> .
  @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

This module does not require L<RDF::Trine>, which is recommended nevertheless.
You should install at least RDF::NS 0.140.  If you prefer RDF::NS to return
instances of L<RDF::Trine::Node::Resource> instead of plain strings, use
L<RDF::NS::Trine>.

The code repository of this module also contains an
L<update script|https://github.com/nichtich/RDF-NS/blob/master/update.pl>
to download the current prefix-namespace mappings from L<http://prefix.cc>.

=head1 METHODS

=head2 new ( $version [, %options ] )

Create a new namespace mapping with a selected version (mandatory). The special
version string C<"any"> can be used to get the newest mapping - actually this
is C<$RDF::NS::VERSION>, but you should better select a specific version, as
mappings can change, violating backwards compatibility. Supported options 
include C<warn> to enable warnings.

=head2 LOAD ( $file [, %options ] )

Load namespace mappings from a particular tab-separated file. See NEW for 
supported options.

=head2 URI ( $short | "<$URI>" )

Expand a prefixed URI, such as C<foaf:Person> or C<foaf_Person>. Alternatively 
you can expand prefixed URIs with method calls, such as C<$ns-E<gt>foaf_Person>.
If you pass an URI wrapped in C<E<lt>> and C<E<gt>>, it will not be expanded
but returned as given.

=head2 TTL ( prefix[es] )

Returns a Turtle/Notation3 C<@prefix> definition or a list of such definitions
in list context. Prefixes can be passed as single arguments or separated by
commas, vertical bars, and spaces.

=head2 SPARQL ( prefix[es] )

Returns a SPARQL PREFIX definition or a list of such definitions in list
context. Prefixes can be passed as single arguments or separated by commas,
vertical bars, and spaces.

=head2 XMLNS ( prefix[es] )

Returns an XML namespace declaration or a list of such declarations in list
context. Prefixes can be passed as single arguments or separated by commas,
vertical bars, and spaces.

=head2 TXT ( prefix[es] )

Returns a list of tabular-separated prefix-namespace-mappings.

=head2 BEACON ( prefix[es] )

Returns a list of BEACON format prefix definitions (not including prefixes).

=head2 SELECT ( prefix[es] )

In list context, returns a sorted list of prefix-namespace pairs, which
can be used to assign to a hash. In scalar context, returns the namespace
of the first prefix that was found. Prefixes can be passed as single arguments
or separated by commas, vertical bars, and spaces.

=head2 MAP ( $code [, prefix[es] ] )

Internally used to map particular or all prefixes. Prefixes can be selected as
single arguments or separated by commas, vertical bars, and spaces. In scalar
context, C<$_> is set to the first existing prefix (if found) and C<$code> is
called. In list context, found prefixes are sorted at mapped with C<$code>.

=head2 GET ( $uri )

This method is used internally to create URIs as return value of the URI
method and all lowercase shortcut methods, such as C<foaf_Person>. By default
it just returns C<$uri> unmodified.

=head1 SEE ALSO

There are several other CPAN modules to deal with IRI namespaces, for instance
L<RDF::Trine::Namespace>, L<RDF::Trine::NamespaceMap>, L<RDF::Prefixes>,
L<RDF::Simple::NS>, L<RDF::RDFa::Parser::Profile::PrefixCC>,
L<Class::RDF::NS>, L<XML::Namespace>, L<XML::CommonNS> etc.

=head1 AUTHOR

Jakob Voss

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2012 by Jakob Voss.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut