On Fri, May 14, 2010 at 12:21:21PM -0400, Jay Savage wrote:
<snip>
> >
> > -------------------- CODE --------------------
> > #!/usr/bin/perl
> > use YAML::Syck;
> > use Data::Dumper;
> >
> > my ($yaml) = Load(<<'...');
> > ---
> > nameserver:
> >  - 172.23.0.5
> >  - 172.23.0.6
> > randomvar:
> >  - elastic
> >  - orange
> >  - clint
> > network:
> >  - eth0:
> >    - ip: 192.168.7.2
> >    - netmask: 255.255.255.0
> > ...
> > #print "yaml: \n", Dump($yaml);
> >
> >
> > my ($yaml2) = Load(<<'...');
> > ---
> > nameserver:
> >  - 192.168.0.1
> >  - 192.168.0.2
> > #network:
> > #  - eth0:
> > #    - ip: 172.23.10.141
> > #    - netmask: 255.255.240.0
> > ...
> > #print "yaml2: \n", Dump($yaml2);
> <snip>
> 
> How are you defining "merge," here? What is your desired result?
> 
> Are you expecting to have a separate node for each nameserver? Or is
> your desired end state a single stream with a singe "nameserver" node
> that has all the ips?
> 
> The first option is pretty simple:
> 
>     my $merged = {NS1 => $yaml1, NS2 => $yaml2};
>     print Dump($merged);
> 
> Your original code was close, but $yaml = ($yaml1, $yaml2) is not a
> valid hashref; it just copies $yaml1 to $yaml and discards $yaml2.
> If you had turned on warnings you would have caught the error.
> *Always* 'use warnings' at the top of your code.
> 
> If your goal is some sort of deeper merge, though, you'll need to
> decide what rule you want to use to resolve conflicts, etc.
> Hash::Merge from CPAN might be a good place to start.
> 
> HTH,
> 
> -- j
> --------------------------------------------------
> This email and attachment(s): [  ] blogable; [ x ] ask first; [  ]
> private and confidential
> 
> daggerquill [at] gmail [dot] com
> http://www.tuaw.com  http://www.downloadsquad.com  http://www.engatiki.org
> 
> values of β will give rise to dom!

Thanks Jay, you helped push me in the right direction here.
I thought I wanted to do a deep merge and end up with mulitple nameservers, but 
on reflection it is better to merge the top level/hash array and have the 
previous value over written. Then new values are appended.

For those interested the solution was very easy:

 -------------------- CODE --------------------
my %merged = {};
sub merge {
while (my $ref = shift)
{
my $k; 
my $v; 
#  print $ref;
  #print Dump($ref);
  while ( ($k,$v) = each(%$ref) )
  {
#    print "\n [ ", $k, " ] = ", $v;
    $merged{$k} = $v; 
  }
  return %merged;
}
} # end sub
 -------------------- CODE --------------------
called by passing in the yaml node to be merged.

Tom

my %merged = {};


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to