Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re: Incrementing a hash of array value

by beable (Friar)
on Jul 23, 2004 at 10:58 UTC ( #376846=note: print w/replies, xml ) Need Help??

in reply to Incrementing a hash of array value

It's not apparent what you are trying to do. Here's your code cleaned up with the syntax errors removed:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash=(); %hash=( ##keys between "" because of dots "M01.001" =>["M01.001"], "M01.001.111" =>["M01.001.111"], "M01.001.111.111" =>["M01.001.111.111"], "M01.002" =>["M01.002"], "M01.002.003" =>["M01.002.003"], ); print Dumper(%hash), "\n"; for my $k(sort keys %hash){ my $temp = reverse($k); $temp =~ s/^\d{3}\.?//; my $t= reverse ($temp); if (exists $hash{$t}){ $hash{$k}[1] += 1; } } print Dumper(%hash); __END__

As for the $hash{$k}[1] += 1; "not working", it is working. It might not be doing what you wanted, but it's doing what somebody would expect, which is to create a second element in the array $hash{$k}, and then add 1 to it, to produce the result 1. If you meant to add 1 to the string "M01.001", what exactly do you think that means? You can't add the integer 1 to a string. It doesn't make sense.

Replies are listed 'Best First'.
Re^2: Incrementing a hash of array value
by Anonymous Monk on Jul 23, 2004 at 21:28 UTC
    Sorry for the dubious code. It's actually a long program. So I just typed the above code from memory hoping it would compile. My apologies! Here is what i am trying to achieve. I have a number of strings which I would like to print in a minimal hierarchical format. Instead of Listing all expanded variations on M01 (ie:
    M01.001 M01.001.111 M01.001.111.111 M01. ... ... ... etc
    I would only like to print "M01.001 +". Then the user can click on the plus sign to expand and view the next level of the tree structure, the children that is. Orphaned nodes would still show but parents would be assigned a plus sign for expansion. The only way I can do this is by counting all occurrences of a certain string in a data reduction technique. I am using a hash of arrays to do this. The first value of the HoA is a string (ie $hash{$k}[0]) in the example; the second element is the incremented number which I autovivify (ie $hash{$k}1). I hope this makes sense. Is there a better technique to do this? Thanks.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://376846]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2023-03-26 02:36 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (63 votes). Check out past polls.