Document-TriPart
view release on metacpan or search on metacpan
lib/Document/TriPart.pm view on Meta::CPAN
$self->{_body_content} = $body;
$self->{_header_content} = $header;
$self->{_preamble_content} = $preamble;
}
return $self;
}
sub _read_until_separator {
my $self = shift;
my $handle = shift;
my $separator = shift;
my $content;
$separator = $self->separator;
my $match = qr/^$separator\s*$/;
my $got_separator;
while (<$handle>) {
last if $got_separator = $_ =~ $match;
$content .= $_;
}
return ($got_separator => \$content);
}
sub _read {
my $self = shift;
my $handle = shift;
local $/ = undef;
my $content;
$content = <$handle>;
return \$content;
}
sub _parse_header {
my $self = shift;
my $content = shift;
# TODO Parsing of: { "a": "1" } does not work
chomp $$content if defined $$content && $$content =~ m/^\s*\{/;
return {} unless my $header = YAML::Tiny->read_string($$content);
return $header->[0];
}
sub _format_header {
my $self = shift;
my $header = shift;
return undef unless defined $header;
croak "Header given is not a hash ($header)" unless ref $header eq 'HASH';
my $string = YAML::Tiny::Dump($header);
$string =~ s/^---\s*//;
return $string;
}
sub _editor {
return [ split m/\s+/, ($ENV{VISUAL} || $ENV{EDITOR}) ];
}
sub _edit_file {
my $file = shift;
die "Don't know what editor" unless my $editor = _editor;
my $rc = system @$editor, $file;
unless ($rc == 0) {
my ($exit_value, $signal, $core_dump);
$exit_value = $? >> 8;
$signal = $? & 127;
$core_dump = $? & 128;
die "Error during edit (@$editor): exit value ($exit_value), signal ($signal), core_dump($core_dump): $!";
}
}
sub edit {
my $self = shift;
my $file;
$file = shift if @_ % 2;
my %given = @_;
$file = $given{file} unless defined $file;
$file = $self->file unless defined $file || $given{tmp};
my ($tmp_fh, $tmp_filename);
unless (defined $file) {
($tmp_fh, $tmp_filename) = tempfile;
$file = $tmp_filename;
# Only write out the file first if we're using a temporary file
$self->write( $file, @_ );
}
_edit_file $file;
$self->read( $file, @_ );
}
1;
__END__
=pod
=head1 NAME
Document::TriPart - Read, write & edit a tri-part document (preamble, YAML::Tiny header, and body)
=head1 VERSION
version 0.024
=head1 SYNOPSIS
my $document;
$document = Document::TriPart::->read( \<<_END_ ); # Or you can use ->read_string( ... )
# vim: #
---
hello: world
---
This is the body
( run in 0.698 second using v1.01-cache-2.11-cpan-71847e10f99 )