473,580 Members | 2,960 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recurse over a hash without knowing any elements (except top level)

I have a hash that is several levels deep.

ie:

'vars' => {
'$filers' => '10.10.10.10/32',
'$networksa' => '10.10.10.10/32',
'$networksb' => '10.50.0.0/16',
'$wintel_boxes' => '10.10.10.10/32',
},
'match' => {
'Rule' => {
'Doug' => {
'RuleSub' => {
'OUTBREAK' => {
Basically a structure similar in nature to that, basically it could go
as deep as 8 keys deep with values potentially with each key, but
usually a value as some level.

I need to iterate over this and print it out in it's structure, but
with some formatting. DataDumper does a fine job of doing it in it's
way, but I cannot customize the pretty output, plus I need to utilize
the data in other ways.

So I figure I can load the "top level" keys (say there are 3 of them),
and then recurse over each subsequent key and gather and print as I
go.

Here is what I tried:

use Config::General ;

my $match_file = qq(match.conf);

my $match_conf = new Config::General (
-file => $match_file,
-AutoTrue => 1);

my %match_config = $match_conf->getall;

$depth = 0;

foreach $key (keys %match_config) {
print "\t"x$depth ;
print "\n$key\n";
$depth++;
&recurse_hash($ match_config{$k ey},$depth);
}

sub recurse_hash {

$match = shift;
$depth = shift;

print "\t"x$depth ;

foreach $key2 (keys %{$match}) {
print "$key2 => $match->{$key2}\n";
($match,$depth) = &recurse_hash($ match->{$key2},$depth );
}
return ($match,$depth) ;
}

I get some results back, but I also get some funk, plus I don't get it
all, just portions..... I have racked my brain on this, and scoured
the groups for anykind of similar problem. Most are only 3 levels
deep, and the levels are known.

Here is the results:
Top level keys are typically gonna be (vars, match, and translate):
vars
$filers =>
$networksa =>
$networksb =>
$wintel_boxes =>

match
Rule => HASH(0x17a918)
DOUG => HASH(0x17a924)
RuleSub => HASH(0x17a99c)
OUTBREAK => HASH(0x17a9a8)
mail_body => blah blahblah
mail_cc =>
page_cc =>
interval =>
GUN =>
DOS =>
PN =>
srcnet =>

translate
CT2 => HASH(0x183a44)
27-74 => HASH(0x183abc)
msg_pattern => HASH(0x183b04)
".*filename : => (.*)" = "Bad file: \1"
27-75 =>
SN =>
MSG =>
Jul 19 '05 #1
2 5022
de**********@ya hoo.com (Christopher) wrote in message news:<e8******* *************** ****@posting.go ogle.com>...
I have a hash that is several levels deep.

ie:

'vars' => {
'$filers' => '10.10.10.10/32',
'$networksa' => '10.10.10.10/32',
'$networksb' => '10.50.0.0/16',
'$wintel_boxes' => '10.10.10.10/32',
},
'match' => {
'Rule' => {
'Doug' => {
'RuleSub' => {
'OUTBREAK' => {
Basically a structure similar in nature to that, basically it could go
as deep as 8 keys deep with values potentially with each key, but
usually a value as some level.

I need to iterate over this and print it out in it's structure, but
with some formatting. DataDumper does a fine job of doing it in it's
way, but I cannot customize the pretty output, plus I need to utilize
the data in other ways.

So I figure I can load the "top level" keys (say there are 3 of them),
and then recurse over each subsequent key and gather and print as I
go.

Here is what I tried:

use Config::General ;

my $match_file = qq(match.conf);

my $match_conf = new Config::General (
-file => $match_file,
-AutoTrue => 1);

my %match_config = $match_conf->getall;

$depth = 0;
You forgot to declare $depth. "use strict" would have told you about
this.
foreach $key (keys %match_config) {
print "\t"x$depth ;
You forgot to declare $key. "use strict" would have told you about
this.
print "\n$key\n";
$depth++;
&recurse_hash($ match_config{$k ey},$depth);
Why is that & in there? Do you know what it does? Do you really want
to do that?

Assuming $depth is supposed to indicate the depth within the
structure, it would be more straight-forward to do

recurse_hash($m atch_config{$ke y},1);

Anyhow it's not clear why you treat the top level specially at all.

recurse_hash(\% match_config,0) ;

}

sub recurse_hash {

$match = shift;
You forgot to declare $match. "use strict" would have told you about
this. By choosing not to "use strict" you instruct Perl to assume any
variable you didn't declare is a package variable and thus a global
variable with respect to the subroutine. Using global variables in
recursive subroutines is bad.
$depth = shift;
Ouch - you forgot to redeclare $depth within the subroutine. "use
strict" would not have helped you directly. But the mind-set that
goes with "use strict" that says "always declare all variables
lexically scoped in the smallest lexical scope" would have made this
error much less likely.
print "\t"x$depth ;
You probably wanted that on each line - i.e inside the loop.
foreach $key2 (keys %{$match}) {
You forgot to declare $key2. "use strict" would have told you about
this.
print "$key2 => $match->{$key2}\n";
($match,$depth) = &recurse_hash($ match->{$key2},$depth );
You are forgetting to check that $match->{$key2} really is a hash ref
either before you call &recurse_has h or within that inner subroutine.
"use strict" would have told you about this because you'd have got an
error when you tried to use something that wasn't a hash ref as a has
ref. Without "use strict" Perl will attempt to convert the string
into a reference by performing a symbol table lookup - this is bad.

Once again assuming $depth is supposed to indicate the depth within
the structure, you should be calling recurse_hash with $depth+1.
}
return ($match,$depth) ;
}
I do not understand why &recurse_has h needs to return this.

sub recurse_hash {

my $match = shift;
my $depth = shift;

return unless ref $match eq 'HASH';

foreach my $key2 (keys %{$match}) {
print "\t"x$depth , "$key2 => $match->{$key2}\n";
recurse_hash($m atch->{$key2},$depth +1);
}
}
I have racked my brain on this, and scoured
the groups for anykind of similar problem.


The consequences of being careles about your variable scoping and
choosing not to "use strict" are often discussed (oftem many times per
day) in the Perl newsgroups that exist. But, of course, you could not
be expected to realise that those are all "similar problems".

I would have thought recursive traversal of Perl structures is
dicussed frequently in the Perl newsgroups that exist. Usually at
least once a month. But actually, having Googled "recursive reference
group:comp.lang .perl.*" it does seem much less common than I'd expect.

Indeed the last thread I could find asking substancially the same
question as you are asking was the sixth hit I got and was way back in
August/September.

That said trawling though six hits isn't all that ownerous. When you
"scoured
the groups for anykind of similar problem" what keywords did you try?

This newsgroup does not (see FAQ). Please do not start threads here.
Jul 19 '05 #2
I appreciate your time to go through my code. I admit that I have been
quite careless, and that I am trying to rectify that habit.

I search on "recurse hash", and probably did not use have the best use
of keywords.

Anway, again thank you for your insight.

-Chris
no****@mail.com wrote in message news:<4d******* *************** ****@posting.go ogle.com>...
de**********@ya hoo.com (Christopher) wrote in message news:<e8******* *************** ****@posting.go ogle.com>...

<snipped>
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2208
by: Cat | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I'm getting a validation error when I try to restrict the content of nested groups with xs:redefine whereas the same restriction on xs:element's validates. ============== BASE XMLSCHEMA ================= <?xml version="1.0"?> <xs:schema targetNamespace="test" xmlns="test"...
22
4590
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last month I had enough of extra proof that the cat doesn't hount mice anymore in more and more situations. And the surrent sicretisme among array and...
35
6613
by: VK | last post by:
Whatever you wanted to know about it but always were affraid to ask. <http://www.geocities.com/schools_ring/ArrayAndHash.html>
2
3771
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to produce two messages having the same message digest. That conjecture is false, as demonstrated by Wang, Feng, Lai and Yu in 2004 . Just recently,...
38
5177
by: VK | last post by:
Hello, In my object I have getDirectory() method which returns 2-dimentional array (or an imitation of 2-dimentional array using two JavaScript objects with auto-handled length property - please let's us do not go into an "each dot over i" clarification discussion now - however you want to call - you call it ;-) array contains records of...
12
3193
by: wxs | last post by:
Many times we have a bunch of enums we have from either different enums or the same enum that will have various numeric values assigned. Rarely will there be collisions in numbering between the enums. These enums you might imagine would be like OrderPrice=27, OrderQuantity=50, OrderSide=62. There may be a lot of these. So normally what we...
9
2148
by: Whybother | last post by:
I have 82,160 3 number combinations (non repeating, like one set of 1,2,3 ; not like 1,2,2) that I'd like create hash keys for with out collision, if possible. I tried SuperFastHash and when I tried loading them to my database I got some primary key failures which would indicate matching keys. I'd like to apply any solution to 4 & 5 number...
13
2513
by: ababeel | last post by:
Hi I am using a calloc in a hash table program on an openvms system. The calloc is used to declare the hash table char **pHashes; pHashes = calloc(hash_size,sizeof(char *)); //hash_size = 101 and then later on when it is half full i do the following char **newHashes; if(newHashes)
139
14087
by: ravi | last post by:
Hi can anybody tell me that which ds will be best suited to implement a hash table in C/C++ thanx. in advanced
0
8132
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8296
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8157
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6533
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5349
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3790
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1394
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1118
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.