perumal has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re: creating hashes recursively
by McDarren (Abbot) on Jun 09, 2006 at 09:13 UTC
    The following works for your given sample data, but I'll be the first to admit that it isn't a very good solution.
    #!/usr/bin/perl -w use strict; use Data::Dumper::Simple; my %data; while (<DATA>) { chomp; my @fields = split /=/; my $depth = scalar @fields; if ($depth == 1) { $data{$fields[0]} = undef; } elsif ($depth == 2) { $data{$fields[0]} = $fields[1]; } elsif ($depth == 3) { $data{$fields[0]}{$fields[1]} = $fields[2]; } } print Dumper(%data); __DATA__ a = ID = 1234 b=Gadens_Melb c= d= e=2006-03-27 15:10:06 f= ContactSensor:INPUT2 g=Critical h=Event-101 fatal stack error on PRI 001

    Output:

    %data = ( 'e' => '2006-03-27 15:10:06', 'c' => undef, 'a ' => { ' ID ' => ' 1234' }, 'h' => 'Event-101 fatal stack error on PRI 001', 'g' => 'Critical', 'b' => 'Gadens_Melb', 'd' => undef, 'f' => ' ContactSensor:INPUT2' );

    Cheers,
    Darren :)

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: hashes recursively
by Moron (Curate) on Jun 09, 2006 at 11:21 UTC
    You don't say what different treatment should be applied inside and outside the info block, so I'll have to skip that for now.

    Here is a recursive solution for an arbitrary depth of hash.

    my %hash=(); Define( \%hash, split /\s*\=\s*/ ) for (split /\n/, $scalar); sub Define { # value returned not used above, # but can be useful for some other cases my $href = shift; my $key = shift or return $href; defined ( $href -> { $key } ) or $href -> { $key } = {}; my $value = shift or return $href -> { $key }; @_ and return Define( $href -> { $key }, $value, @_ ); return $href -> { $key } = $value; }

    -M

    Free your mind

Re: hashes recursively
by Jasper (Chaplain) on Jun 09, 2006 at 13:52 UTC
    sub hasher { shift(), (@_ ? $#_ ? { &hasher } : @_ : return) } my %hash; while (<DATA>) { chomp; my @a = hasher(split /=/); $hash{ $a[0] } = $a[1] if @a == 2; } use Data::Dumper; print Dumper \%hash; __DATA__ a = ID = 1234 = this is the next bit = fifteen = 19.168.0.2 <<Start of info>> b=Gadens_Melb c= d= e=2006-03-27 15:10:06 f= ContactSensor:INPUT2 g=Critical h=Event-101 fatal stack error on PRI 001

    gives me
    $VAR1 = { 'e' => '2006-03-27 15:10:06', 'a ' => { ' ID ' => { ' 1234 ' => { ' this is the next bit ' + => { + ' fifteen ' => ' 19.168.0.2' + } } } }, 'h' => 'Event-101 fatal stack error on PRI 001', 'g' => 'Critical', 'b' => 'Gadens_Melb', 'f' => ' ContactSensor:INPUT2' };
    That looks like what you wanted. Dunno how it works, though.