Tie::YAML - Stores your object when untied via YAML


Tie-SaveLater documentation Contained in the Tie-SaveLater distribution.

Index


Code Index:

NAME

Top

Tie::YAML - Stores your object when untied via YAML

SYNOPSIS

Top

  use Tie::YAML;
  {
      tie my $scalar => 'Tie::YAML', 'scalar.po';
      $scalar = 42;
  } # scalar is automatically saved as 'scalar.po'.
  {
      tie my @array => 'Tie::YAML', 'array.po';
      @array = qw(Sun Mon Tue Wed Fri Sat);
  } # array is automatically saved as 'array.po'.
  {
      tie my %hash => 'Tie::YAML', 'hash.po';
      %hash = (Sun=>0, Mon=>1, Tue=>2, Wed=>3, Thu=>4, Fri=>5, Sat=>6);
  } # hash is automatically saved as 'hash.po'.
  {
      tie my $object => 'Tie::YAML', 'object.po';
      $object = bless { First => 'Dan', Last => 'Kogai' }, 'DANKOGAI';
  } # You can save an object; just pass a scalar
  {
      tie my $object => 'Tie::YAML', 'object.po';
      $object->{WIFE} =  { First => 'Naomi', Last => 'Kogai' };
      # you can save before you untie like this
      tied($object)->save;
  }

DESCRIPTION

Top

Tie::YAML stores tied variables when untied. Usually that happens when you variable is out of scope. You can of course explicitly untie the variable or tied($variable)->save but the whole idea is not to forget to save it.

This module uses YAML as its backend so it can store and retrieve anything that YAML can.

DEPENDENCIES

Top

This module requires YAML.

SEE ALSO

Top

Tie::SaveLater, Tie::DataDumper, Tie::Storable

perltie, Tie::Scalar, Tie::Array, Tie::Hash

BUGS

Top

As of YAML 0.58, YAML cannot serialize a blessed scalar reference to blessed scalar reference. For that reason, I had to implement a funcition that looks like this.

  sub damn_scalar { # iff necessary
    return $_[0] unless ref($_[0]) =~ /::SCALAR$/;
    return \do{ my $scalar = ${ $_[0] }}
  }

Sigh.

AUTHOR

Top

Dan Kogai, <dankogai@dan.co.jp>

COPYRIGHT AND LICENSE

Top


Tie-SaveLater documentation Contained in the Tie-SaveLater distribution.

#
# $Id: YAML.pm,v 0.3 2006/03/22 22:10:28 dankogai Exp $
#
package Tie::YAML;
use strict;
use warnings;
our $VERSION = sprintf "%d.%02d", q$Revision: 0.3 $ =~ /(\d+)/g;
use base 'Tie::SaveLater';
use Carp;
use YAML;
__PACKAGE__->make_subclasses;

sub load{ 
    my $class = shift;
    my $filename = shift; 
    open my $fh, "<:raw", $filename or croak "$filename: $!";
    local $/; # slurp;
    my $yaml = <$fh>;
    close $fh;
    return Load($yaml);
}

sub save{
    my $self = shift;
    my $filename = $self->filename;
    open my $fh, ">:raw", $filename or croak "$filename: $!";
    print $fh Dump(damn_scalar($self));
    close $fh;
    return 1;
} 

sub damn_scalar { # iff necessary
    return $_[0] unless ref($_[0]) =~ /::SCALAR$/;
    return \do{ my $scalar = ${ $_[0] }}
}
1;
__END__