📄 yaml.pm
字号:
package YAML;use strict; use warnings;use YAML::Base;use base 'YAML::Base';use YAML::Node; # XXX This is a temp fix for Module::Builduse 5.006001;our $VERSION = '0.66';our @EXPORT = qw'Dump Load';our @EXPORT_OK = qw'freeze thaw DumpFile LoadFile Bless Blessed';# XXX This VALUE nonsense needs to go.use constant VALUE => "\x07YAML\x07VALUE\x07";# YAML Object Propertiesfield dumper_class => 'YAML::Dumper';field loader_class => 'YAML::Loader';field dumper_object => -init => '$self->init_action_object("dumper")';field loader_object => -init => '$self->init_action_object("loader")';sub Dump { my $yaml = YAML->new; $yaml->dumper_class($YAML::DumperClass) if $YAML::DumperClass; return $yaml->dumper_object->dump(@_);}sub Load { my $yaml = YAML->new; $yaml->loader_class($YAML::LoaderClass) if $YAML::LoaderClass; return $yaml->loader_object->load(@_);}{ no warnings 'once'; # freeze/thaw is the API for Storable string serialization. Some # modules make use of serializing packages on if they use freeze/thaw. *freeze = \ &Dump; *thaw = \ &Load;}sub DumpFile { my $OUT; my $filename = shift; if (ref $filename eq 'GLOB') { $OUT = $filename; } else { my $mode = '>'; if ($filename =~ /^\s*(>{1,2})\s*(.*)$/) { ($mode, $filename) = ($1, $2); } open $OUT, $mode, $filename or YAML::Base->die('YAML_DUMP_ERR_FILE_OUTPUT', $filename, $!); } local $/ = "\n"; # reset special to "sane" print $OUT Dump(@_);}sub LoadFile { my $IN; my $filename = shift; if (ref $filename eq 'GLOB') { $IN = $filename; } else { open $IN, $filename or YAML::Base->die('YAML_LOAD_ERR_FILE_INPUT', $filename, $!); } return Load(do { local $/; <$IN> });}sub init_action_object { my $self = shift; my $object_class = (shift) . '_class'; my $module_name = $self->$object_class; eval "require $module_name"; $self->die("Error in require $module_name - $@") if $@ and "$@" !~ /Can't locate/; my $object = $self->$object_class->new; $object->set_global_options; return $object;}my $global = {};sub Bless { require YAML::Dumper::Base; YAML::Dumper::Base::bless($global, @_)}sub Blessed { require YAML::Dumper::Base; YAML::Dumper::Base::blessed($global, @_)}sub global_object { $global }1;__END__=head1 NAMEYAML - YAML Ain't Markup Language (tm)=head1 SYNOPSIS use YAML; # Load a YAML stream of 3 YAML documents into Perl data structures. my ($hashref, $arrayref, $string) = Load(<<'...'); --- name: ingy age: old weight: heavy # I should comment that I also like pink, but don't tell anybody. favorite colors: - red - green - blue --- - Clark Evans - Oren Ben-Kiki - Ingy d枚t Net --- > You probably think YAML stands for "Yet Another Markup Language". It ain't! YAML is really a data serialization language. But if you want to think of it as a markup, that's OK with me. A lot of people try to use XML as a serialization format. "YAML" is catchy and fun to say. Try it. "YAML, YAML, YAML!!!" ... # Dump the Perl data structures back into YAML. print Dump($string, $arrayref, $hashref); # YAML::Dump is used the same way you'd use Data::Dumper::Dumper use Data::Dumper; print Dumper($string, $arrayref, $hashref); =head1 DESCRIPTIONThe YAML.pm module implements a YAML Loader and Dumper based on the YAML1.0 specification. L<http://www.yaml.org/spec/>YAML is a generic data serialization language that is optimized forhuman readability. It can be used to express the data structures of mostmodern programming languages. (Including Perl!!!)For information on the YAML syntax, please refer to the YAMLspecification.=head1 WHY YAML IS COOL=over 4=item YAML is readable for people. It makes clear sense out of complex data structures. You should findthat YAML is an exceptional data dumping tool. Structure is shownthrough indentation, YAML supports recursive data, and hash keys aresorted by default. In addition, YAML supports several styles of scalarformatting for different types of data.=item YAML is editable.YAML was designed from the ground up to be an excellent syntax forconfiguration files. Almost all programs need configuration files, sowhy invent a new syntax for each one? And why subject users to thecomplexities of XML or native Perl code?=item YAML is multilingual.Yes, YAML supports Unicode. But I'm actually referring to programminglanguages. YAML was designed to meet the serialization needs of Perl,Python, Ruby, Tcl, PHP, Javascript and Java. It was also designed to beinteroperable between those languages. That means YAML serializationsproduced by Perl can be processed by Python.=item YAML is taint safe.Using modules like Data::Dumper for serialization is fine as long as youcan be sure that nobody can tamper with your data files ortransmissions. That's because you need to use Perl's C<eval()> built-into deserialize the data. Somebody could add a snippet of Perl to eraseyour files.YAML's parser does not need to eval anything.=item YAML is full featured.YAML can accurately serialize all of the common Perl data structures anddeserialize them again without losing data relationships. Although it isnot 100% perfect (no serializer is or can be perfect), it fares as wellas the popular current modules: Data::Dumper, Storable, XML::Dumper andData::Denter.YAML.pm also has the ability to handle code (subroutine) references andtypeglobs. (Still experimental) These features are not found in Perl'sother serialization modules.=item YAML is extensible.The YAML language has been designed to be flexible enough to solve it'sown problems. The markup itself has 3 basic construct which resemblePerl's hash, array and scalar. By default, these map to their Perlequivalents. But each YAML node also supports a tagging mechanism (typesystem) which can cause that node to be interpreted in a completelydifferent manner. That's how YAML can support object serialization andoddball structures like Perl's typeglob.=back=head1 YAML IMPLEMENTATIONS IN PERLThis module, YAML.pm, is really just the interface module for YAMLmodules written in Perl. The basic interface for YAML consists of twofunctions: C<Dump> and C<Load>. The real work is done by the modulesYAML::Dumper and YAML::Loader.Different YAML module distributions can be created by subclassingYAML.pm and YAML::Loader and YAML::Dumper. For example, YAML-Simpleconsists of YAML::Simple YAML::Dumper::Simple and YAML::Loader::Simple.Why would there be more than one implementation of YAML? Well, despiteYAML's offering of being a simple data format, YAML is actually verydeep and complex. Implementing the entirety of the YAML specification isa daunting task.For this reason I am currently working on 3 different YAML implementations.=over=item YAMLThe main YAML distribution will keeping evolving to support the entireYAML specification in pure Perl. This may not be the fastest or moststable module though. Currently, YAML.pm has lots of known bugs. It ismostly a great tool for dumping Perl data structures to a readable form.=item YAML::LiteThe point of YAML::Lite is to strip YAML down to the 90% that peopleuse most and offer that in a small, fast, stable, pure Perl form.YAML::Lite will simply die when it is asked to do something it can't.=item YAML::SyckC<libsyck> is the C based YAML processing library used by the Rubyprogramming language (and also Python, PHP and Pugs). YAML::Syck is thePerl binding to C<libsyck>. It should be very fast, but may haveproblems of its own. It will also require C compilation.NOTE: Audrey Tang has actually completed this module and it works great and is 10 times faster than YAML.pm.=backIn the future, there will likely be even more YAML modules. Remember,people other than Ingy are allowed to write YAML modules!=head1 FUNCTIONAL USAGEYAML is completely OO under the hood. Still it exports a few useful toplevel functions so that it is dead simple to use. These functions justdo the OO stuff for you. If you want direct access to the OO API see thedocumentation for YAML::Dumper and YAML::Loader.=head2 Exported FunctionsThe following functions are exported by YAML.pm by default. The reasonthey are exported is so that YAML works much like Data::Dumper. If youdon't want functions to be imported, just use YAML with an emptyimport list: use YAML ();=over 4=item Dump(list-of-Perl-data-structures)Turn Perl data into YAML. This function works very much likeData::Dumper::Dumper(). It takes a list of Perl data strucures anddumps them into a serialized form. It returns a string containing theYAML stream. The structures can be references or plain scalars.=item Load(string-containing-a-YAML-stream) Turn YAML into Perl data. This is the opposite of Dump. Just likeStorable's thaw() function or the eval() function in relation toData::Dumper. It parses a string containing a valid YAML stream into alist of Perl data structures.=back=head2 Exportable FunctionsThese functions are not exported by default but you can request them inan import list like this: use YAML qw'freeze thaw Bless';=over 4=item freeze() and thaw()Aliases to Dump() and Load() for Storable fans. This will also allowYAML.pm to be plugged directly into modules like POE.pm, that use thefreeze/thaw API for internal serialization.=item DumpFile(filepath, list)Writes the YAML stream to a file instead of just returning a string.=item LoadFile(filepath)Reads the YAML stream from a file instead of a string.=item Bless(perl-node, [yaml-node | class-name])Associate a normal Perl node, with a yaml node. A yaml node is an objecttied to the YAML::Node class. The second argument is either a yaml nodethat you've already created or a class (package) name that supports ayaml_dump() function. A yaml_dump() function should take a perl node andreturn a yaml node. If no second argument is provided, Bless will createa yaml node. This node is not returned, but can be retrieved with theBlessed() function.Here's an example of how to use Bless. Say you have a hash containingthree keys, but you only want to dump two of them. Furthermore the keysmust be dumped in a certain order. Here's how you do that: use YAML qw(Dump Bless); $hash = {apple => 'good', banana => 'bad', cauliflower => 'ugly'}; print Dump $hash; Bless($hash)->keys(['banana', 'apple']); print Dump $hash;produces: --- apple: good banana: bad cauliflower: ugly --- banana: bad apple: goodBless returns the tied part of a yaml-node, so that you can call theYAML::Node methods. This is the same thing that YAML::Node::ynode()returns. So another way to do the above example is: use YAML qw(Dump Bless); use YAML::Node; $hash = {apple => 'good', banana => 'bad', cauliflower => 'ugly'}; print Dump $hash; Bless($hash); $ynode = ynode(Blessed($hash)); $ynode->keys(['banana', 'apple']); print Dump $hash;Note that Blessing a Perl data structure does not change it anyway. Theextra information is stored separately and looked up by the Blessednode's memory address.=item Blessed(perl-node)Returns the yaml node that a particular perl node is associated with(see above). Returns undef if the node is not (YAML) Blessed.=back=head1 GLOBAL OPTIONSYAML options are set using a group of global variables in the YAMLnamespace. This is similar to how Data::Dumper works.For example, to change the indentation width, do something like: local $YAML::Indent = 3;The current options are:=over 4=item DumperClassYou can override which module/class YAML uses for Dumping data.=item LoaderClassYou can override which module/class YAML uses for Loading data.=item Indent
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -