Hi,
I was trying to find a way to have data stored in the program script
itself a la perl5 __DATA__. Perl6 has the =data pod structures to do
that. But after a first test I got an error using $=data saying that it
was not yet implemented. But, as the saying goes, there's more than one
way to do it!
First I still wanted to use the '=begin data' and '=end data' pod
statements to store data and just search through the pod data myself.
The problem I found however was that the newline characters were removed
from the text. This is inconvenient. Looking at other pod thingies I saw
that the pod comment was very usable in that everything was left as it
was typed in. I've developed a small sub which makes use of comment
blocks and interprets them as a data block.
E.g.
=begin comment :!comment :type<fooData>
# test van data
foo 1
# second line
bar 2
=end comment
# get and use the data
my Str $foo-data = get-data('fooData');
for $foo-data.lines -> $line {
say "Data line: $line";
}
# Program returns;
#Data line: foo 1
#Data line: bar 2
A few things to mention here;
1) :!comment is checked by the sub so it must be there. It is also a
sign to the reader that this block is not used to show comments.
2) :fooData is the key to use to search for data. More than one data
block is then possible and other (real) comments are not processed.
3) The sub is filtering out empty lines and comment lines (starting with
'#').
The sub is shown below;
sub get-data ( Str:D $content-key --> Str ) {
my Str $content;
# search through the pod structure
for @$=pod -> $pd {
# search for 1) pod comment block, 2) :!comment and 3) the users key
if $pd ~~ Pod::Block::Comment and
!$pd.config<comment> and
$pd.config<type> eq $content-key {
$content = $pd.contents[0];
last;
}
}
# remove comments
$content ~~ s:g/\s* '#' .*? $$//;
# remove empty lines
$content ~~ s:g/^^ \s* $$//;
$content ~~ s:g/\n\n+/\n/;
$content ~~ s:g/^\n+//;
$content ~~ s:g/\n+$//;
$content
}
You can get this program from a gist at github here;
https://gist.github.com/MARTIMM/516b3ade0500428cedc28ae86fad6a1b
Hopefully anyone can profit from this code,
cheers,
Marcel