On Thu, Mar 3, 2011 at 5:40 PM, Jim Green
<student.northwest...@gmail.com> wrote:
> manually populate another hash and dump. But is there a easier way of
> doing this I might not be aware of?

I don't know if I'd call it easier. I'm not personally familiar with
YAML so I only bothered to parse the example that you gave.

#!/usr/bin/env perl

use strict;
use warnings;

my %inverted_data;
my $subkey;

while(my $line = <DATA>)
{
    chomp $line;

    if(my ($key) = $line =~ /^([^:]+):$/)
    {
        $subkey = $key;
    }

    if(my ($key, $value) = $line =~ /^\s*([^:]+):([^:]+)$/)
    {
        $inverted_data{$key}->{$subkey} = $value;
    }
}

for my $key (keys %inverted_data)
{
    print "$key:\n";

    for my $subkey (keys %{$inverted_data{$key}})
    {
        print "  $subkey:$inverted_data{$key}->{$subkey}\n";
    }
}

__DATA__
key1:
a: value1
b: value1
key2:
a: value2
b: value2

If a module exists to parse YAML then you might as well use it (unless
there's a good technical reason not to). Some Perl veterans can
probably reduce this to couple of lines. :P

-- 
Brandon McCaig <http://www.bamccaig.com/> <bamcc...@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org>

-- 
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