Subject: | Have YAML::Loader load classes on-the-fly? |
Loading YAML files might be cleaner if the loader would also attempt to
load any classes used. The attached unified diff represents one way to
do this. The _try_load subroutine actually returns a value, but no use
is made of it.
Maybe you have something else in the works, though, or some good
architectural reason not to do this. But I figured it would not hurt to
make the suggestion.
Thanks for your time and attention,
Tom Wyant
Subject: | YAML-Loader.diff |
--- Loader.old Fri Jun 30 17:27:22 2006
+++ Loader.pm Mon Jul 24 15:06:09 2006
@@ -189,6 +189,7 @@
undef $node;
$node = \$copy;
}
+ _try_load ($class) if $YAML::Loader::LoadClass; # trw
CORE::bless $node, $class;
}
else {
@@ -253,9 +254,11 @@
if ($explicit =~ /^\!perl\/(hash|array|scalar)\:(\w(\w|\:\:)*)?$/) {
($type, $class) = (($1 || ''), ($2 || ''));
if (ref $node) {
+ _try_load ($class) if $YAML::Loader::LoadClass; # trw
return CORE::bless $node, $class;
}
else {
+ _try_load ($class) if $YAML::Loader::LoadClass; # trw
return CORE::bless \$node, $class;
}
}
@@ -282,9 +285,11 @@
}
else {
if (ref $node) {
+ _try_load ($class) if $YAML::Loader::LoadClass; # trw
return CORE::bless $node, $class;
}
else {
+ _try_load ($class) if $YAML::Loader::LoadClass; # trw
return CORE::bless \$node, $class;
}
}
@@ -711,6 +716,23 @@
#==============================================================================
# Utility subroutines.
#==============================================================================
+
+# Modules we have already tried to load. # trw
+my %tried_load;
+
+# Try to load the module before we bless the object. # trw
+sub _try_load {
+ my $mod = shift;
+ return $tried_load{$mod} if exists $tried_load{$mod};
+ (my $fn = $mod) =~ s|::|/|g;
+ $fn .= '.pm';
+ if ($INC{$fn}) {
+ $tried_load{$mod} = $fn;
+ } else {
+ eval {require $fn};
+ $tried_load{$mod} = $@ ? undef : $fn;
+ }
+}
# Printable characters for escapes
my %unescapes =