logo
down
shadow

Perl - traversing hash of (hashes of hashes and scalars)?


Perl - traversing hash of (hashes of hashes and scalars)?

By : Perry McKenzie
Date : November 19 2020, 03:01 PM
To fix this issue I have generated a hash that looks like this. (printed using Dumper)
code :
for my $key (keys(%$VAR1)) {
   my $rec = $VAR1->{$key};

   my $cur_ver = $rec->{curVer};
   my $subrec  = $rec->{"version.$cur_ver"};

   my $checksum_new = $subrec->{'checksum.new'};
   my $checksum_old = $subrec->{'checksum.old'};
   my $name         = $subrec->{name};
   my $path         = $subrec->{path};

   ...
}


Share : facebook icon twitter icon
How can I create a hash of hashes from an array of hashes in Perl?

How can I create a hash of hashes from an array of hashes in Perl?


By : Gugu Faustino
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I have an array of hashes, all with the same set of keys, e.g.:
code :
use Data::Dumper;

my $aoa= [
 {NAME=>'Dave', AGE=>12, SEX=>'M', ID=>123456, NATIONALITY=>'Swedish'},
 {NAME=>'Susan', AGE=>36, SEX=>'F', ID=>543210, NATIONALITY=>'Swedish'},
 {NAME=>'Bart', AGE=>120, SEX=>'M', ID=>987654, NATIONALITY=>'British'},
];

sub aoh_to_hoh {
  my ($aoa, $key_hierarchy_a) = @_;
  my $result = {};
  my $last_key = $key_hierarchy_a->[-1];
  foreach my $orig_element (@$aoa) {
    my $cur = $result;
    # song and dance to clone an element
    my %element = %$orig_element;
    foreach my $key (@$key_hierarchy_a) {
      my $value = delete $element{$key};
      if ($key eq $last_key) {
        $cur->{$value} ||= [];
        push @{$cur->{$value}}, \%element;
      } else {
        $cur->{$value} ||= {};
        $cur = $cur->{$value};
      }
    }
  }
  return $result;
}

my $key_hierarchy_a = ['SEX', 'NATIONALITY'];
print Dumper(aoh_to_hoh($aoa, $key_hierarchy_a));
$VAR1 = {
          'F' => {
                   'Swedish' => [
                                  {
                                    'ID' => 543210,
                                    'NAME' => 'Susan',
                                    'AGE' => 36
                                  }
                                ]
                 },
          'M' => {
                   'British' => [
                                  {
                                    'ID' => 987654,
                                    'NAME' => 'Bart',
                                    'AGE' => 120
                                  }
                                ],
                   'Swedish' => [
                                  {
                                    'ID' => 123456,
                                    'NAME' => 'Dave',
                                    'AGE' => 12
                                  }
                                ]
                 }
        };
Can BerkeleyDB in perl handle a hash of hashes of hashes (up to n)?

Can BerkeleyDB in perl handle a hash of hashes of hashes (up to n)?


By : Yavor
Date : March 29 2020, 07:55 AM
Does that help Use DBM::Deep.
code :
my $db = DBM::Deep->new( "foo.db" );

$db->{mykey} = "myvalue";
$db->{myhash} = {};
$db->{myhash}->{subkey} = "subvalue";

print $db->{myhash}->{subkey} . "\n";
sub get_node {
   my $p = \shift;
   $p = \( ($$p)->{$_} ) for @_;
   return $p;
}

my @seqs = qw( CG CA TT CG );

my $tree = DBM::Deep->new("foo.db");
++${ get_node($tree, split //) } for @seqs;
Iterating over Perl hash of hashes and array of hashes

Iterating over Perl hash of hashes and array of hashes


By : Sarathbabu
Date : March 29 2020, 07:55 AM
like below fixes the issue I think you are using XML::Simple? If so you would be far better off using an XML parser that gives you XPath-like access to your data, such as XML::LibXML or XML::Twig.
As it stands you would be better off maintaining scalar variables to point at each step inside the hash structure. That would avoid multiple keys to access an element as well as using the same hash access repeatedly. You shouldn't copy to another hash as you do in my %sw = %{ $sw->{'Product'} } because there is no point in copying all the hash keys and values. I have used my $products = $sw->{Product} in the code below, and then my $product = $products->{$prodname} and my $pv = $product->{ProductVersion}.
code :
my $products = $sw->{Product};

foreach my $prodname (keys %$products) {

    print "\n\nNow processing $prodname\n";

    my $product = $products->{$prodname};

    my ($description, $vendorUniqueKeyRef, $swUniqueKey) =
            @$product{qw/ description vendorUniqueKeyRef swUniqueKey /};

    my @versions;
    if (my $pv = $product->{ProductVersion}) {
        for my $ver (exists $pv->{version} ? $pv : values %$pv) {
          push @versions, sprintf "%d.%d",
              $ver->{version} // 0,
              $ver->{ProductVersionRelease}{release} // 0;
        }
    } 

    print "***************\n";
    print "The product is: $prodname\n";
    print "The description is: $description\n";
    print "The vendorUniqueKeyRef is: $vendorUniqueKeyRef\n";
    print "The ProductVersion is: $_\n" for @versions;
    print "The swUniqueKey is: $swUniqueKey\n";
    print "***************\n";
}
Now processing DB2 Utilities Suite for z/OS
***************
The product is: DB2 Utilities Suite for z/OS
The description is: DB2 Utilities Suite for z/OS
The vendorUniqueKeyRef is: IBM
The ProductVersion is: 9.0
The ProductVersion is: 7.0
The swUniqueKey is: DB2UTSU
***************

Now processing UMB
***************
The product is: UMB
The description is: UMB
The vendorUniqueKeyRef is: CSC
The swUniqueKey is: CSCUMB
***************

Now processing EREP Environmental Recording Edit Print
***************
The product is: EREP Environmental Recording Edit Print
The description is: EREP Environmental Recording Edit Print
The vendorUniqueKeyRef is: IBM
The ProductVersion is: 3.0
The swUniqueKey is: EREP
***************

Now processing Unicenter CA-JCLCheck Utility
***************
The product is: Unicenter CA-JCLCheck Utility
The description is: Unicenter CA-JCLCheck Utility
The vendorUniqueKeyRef is: CA
The swUniqueKey is: JCLCHECK
***************

Now processing Unicenter CA-Deliver Output Management
***************
The product is: Unicenter CA-Deliver Output Management
The description is: Unicenter CA-Deliver Output Management
The vendorUniqueKeyRef is: CA
The swUniqueKey is: RMO
***************

Now processing 3270-PC File Transfer Program
***************
The product is: 3270-PC File Transfer Program
The description is: 3270-PC File Transfer Program
The vendorUniqueKeyRef is: IBM
The swUniqueKey is: 3270PCFT
***************

Now processing SYSQL
***************
The product is: SYSQL
The description is: SYSQL
The vendorUniqueKeyRef is: SPLWDGRP
The ProductVersion is: 2.1
The swUniqueKey is: SYSQL
***************

Now processing Tivoli OMEGAMON XE for Messaging for z/OS
***************
The product is: Tivoli OMEGAMON XE for Messaging for z/OS
The description is: Tivoli OMEGAMON XE for Messaging for z/OS
The vendorUniqueKeyRef is: IBM
The swUniqueKey is: OMXEMES
***************

Now processing Tivoli OMEGAMON XE on z/OS
***************
The product is: Tivoli OMEGAMON XE on z/OS
The description is: Tivoli OMEGAMON XE on z/OS
The vendorUniqueKeyRef is: IBM
The ProductVersion is: 3.0
The swUniqueKey is: OMXEZO
***************
Perl hash of hashes of hashes of hashes... is there an 'easy' way to get an element at the end of the list?

Perl hash of hashes of hashes of hashes... is there an 'easy' way to get an element at the end of the list?


By : Scott MB
Date : March 29 2020, 07:55 AM
this one helps. $person is the key, to shorten things for the inner loops you need to assign the value to something:
code :
foreach my $person_key (sort keys %$people) {
    my $person = $people->{$person_key};
    my $names  = $person->{NAMES};
    foreach my $name (sort keys %$names) {
Perl, create hash of hashes tree from array of hashes

Perl, create hash of hashes tree from array of hashes


By : innocent tauzeni
Date : March 29 2020, 07:55 AM
Does that help Update
My apologies. I missed your final paragraph that explained how an item may have a spurious parent "1" in addition to the real value. I've added some code to sanitise the original data and create a map %parent of every node to its true parent before building the graph
code :
use strict;
use warnings 'all';

use Graph::Directed;

my @arr = (

    #subways, "0" - superroot
    { id => "1", parent_id => "0", name => "subway 1" },

    #lines
    { id => "12642", parent_id => "1", name => "no category" },
    { id => "12645", parent_id => "1", name => "line 1" },

    #cars
    { id => "12646", parent_id => "1",     name => "carriage 1" },
    { id => "12646", parent_id => "12645", name => "carriage 1" },
    { id => "12647", parent_id => "1",     name => "carriage 2" },
    { id => "12647", parent_id => "12645", name => "carriage 2" },
    { id => "12679", parent_id => "1",     name => "separate cars" },
    { id => "12679", parent_id => "12642", name => "separate cars" },
    { id => "12643", parent_id => "1",     name => "ungrouped" },
    { id => "12643", parent_id => "12642", name => "ungrouped" }
);

# Sanitise data to remove "1" parents
#
my %parent;

for my $node ( @arr ) {
    my ($id, $parent_id) = @{$node}{qw/ id parent_id /};
    next unless $parent_id;
    $parent{$id} = $parent_id unless $parent{$id} and $parent{$id} ne 1;
}

# Build the graph
#
my $tree = Graph::Directed->new;

for my $node ( keys %parent ) {
    $tree->add_edge( $parent{$node} => $node );
}

# Display the data
#
my %names = map { @{$_}{qw/ id name /} } @arr;

print_tree($tree, $_) for $tree->predecessorless_vertices;

sub print_tree {
    my ($tree, $root, $indent) = @_;
    $indent //= 0;

    printf "%s%s\n",  '    ' x $indent, $names{$root};

    print_tree($tree, $_, $indent + 1) for $tree->successors($root);
}
subway 1
    line 1
        carriage 1
        carriage 2
    no category
        separate cars
        ungrouped
use strict;
use warnings 'all';

use Graph::Directed;

my @arr = (

    #subways, "0" - superroot
    { id => "1", parent_id => "0", name => "subway 1" },

    #lines
    { id => "12642", parent_id => "1", name => "no category" },
    { id => "12645", parent_id => "1", name => "line 1" },

    #cars
    { id => "12646", parent_id => "1",     name => "carriage 1" },
    { id => "12646", parent_id => "12645", name => "carriage 1" },
    { id => "12647", parent_id => "1",     name => "carriage 2" },
    { id => "12647", parent_id => "12645", name => "carriage 2" },
    { id => "12679", parent_id => "1",     name => "separate cars" },
    { id => "12679", parent_id => "12642", name => "separate cars" },
    { id => "12643", parent_id => "1",     name => "ungrouped" },
    { id => "12643", parent_id => "12642", name => "ungrouped" }
);

# Build the graph
#
my $tree = Graph::Directed->new;

for my $node ( @arr ) {
    $tree->add_edge( @{$node}{qw/ parent_id id /} ) if $node->{parent_id};
}

# Display the structure
#
my %names = map { @{$_}{qw/ id name /} } @arr;

print_tree($tree, $_) for $tree->predecessorless_vertices;

sub print_tree {
    my ($tree, $root, $indent) = @_;
    $indent //= 0;

    printf "%s%s\n",  '    ' x $indent, $names{$root};

    print_tree($tree, $_, $indent + 1) for $tree->successors($root);
}
subway 1
    no category
        ungrouped
        separate cars
    carriage 2
    carriage 1
    separate cars
    ungrouped
    line 1
        carriage 2
        carriage 1
Related Posts Related Posts :
  • Parsing AutoSys JIL with perl
  • Calling methods from a class via another class which uses it
  • How can I get the symbols in a package at the time the package is defined?
  • Perl random string, but doesn't seem so random when used in a browser
  • How to display the special value always at top while sorting?
  • How to handle quotes in Perl when calling system commands?
  • Different results iterating over a hash in Perl
  • Turn Query String into Hash Perl
  • How to identify the format of the given date in perl
  • Is an object accessible if not assigned to any variable?
  • Mapping array additionally to existing hash in Perl
  • Why are leading-hyphen options permitted on `use` lines without fat comma and with strict?
  • sub sample an array with an index array
  • How do I get the last modified date of a directory?
  • Perl GD module PNG image corrupt or cant open
  • Perl not finding data files
  • How to fix UTF-8 encoding error with Russian words
  • How to get query string parameters from POST request in CGI Perl script?
  • How to create properties file inside perl script
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org